代码之家  ›  专栏  ›  技术社区  ›  Kyle Krull

Hibernate:如何急切地获取未关联的实体?

  •  1
  • Kyle Krull  · 技术社区  · 16 年前

    public class InitConfig {
    
        private final SessionFactory sessionFactory;
        private final NodeManager nodeManager;
    
        public void run() {
    
            final Configuration config = new Configuration("NewConfiguration", new HashSet<Node> ());
            for(String name : lotsOfNames) {
    
                //Lots of these queries run slowly
                final Node node = this.nodeManager.getNode(name);
                config.addNode(node);
            }
            this.sessionFactory.getCurrentSession().save(config);
        }
    }
    

    相关的DAO(NodeManager)和慢速查询实体(Node)看起来像这样:

    public class NodeManager {
    
        private final SessionFactory sessionFactory;
    
        public Node getNode(String name) {
    
            final Session db = this.sessionFactory.getCurrentSession();
            final Query query = db.createQuery("from NODE where NAME = :name");
            query.setString("name", name);
            return (Node)query.uniqueResult();
        }
    }
    
    @Entity(name="NODE")
    public class Node {
    
        @GeneratedValue(strategy=GenerationType.TABLE)
        @Id @Column(name="ID")
        private Long id;
    
        private @Column(name="NAME", nullable=false, unique=true) String name;
    
        //Other properties and associations...
    }
    

    @Entity(name="CONFIGURATION")
    public class Configuration {
    
        @Id @GeneratedValue @Column(name="ID")
        private Long id;
        private @Column(name="NAME", nullable=false, unique=true) String name;
    
        @ManyToMany
        @JoinTable(
            name="CONFIGURATION_NODE",
            joinColumns=@JoinColumn(name="CONFIGURATION_ID", nullable=false),
            inverseJoinColumns=@JoinColumn(name="NODE_ID", nullable=false))
        private Set<Node> nodes = new HashSet<Node> ();
    
        public void addNode(Node node) {
    
            this.nodes.add(node);
        }
    }
    

    • Hibernate的二级缓存是否适用于此,如果适用,我该如何配置它?
    • 如果没有,还有其他Hibernate功能可以在这里使用吗?

    1 回复  |  直到 16 年前
        1
  •  2
  •   ChssPly76    16 年前

    Configuration.addNode()

    1. lotsOfNames
    2. name IN(?)