Hibernate加载已经手动设置的实体

时间:2014-07-10 00:21:42

标签: java hibernate jpa hibernate-mapping

我有一个实体

@Entity
public class A {
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "B_ID")
    B classB;
}

@Entity
public class B {
    @OneToMany(mappedBy = "classB")
    @OnDelete(action = OnDeleteAction.CASCADE)
    @LazyCollection(LazyCollectionOption.TRUE)
    List<A> classACollection;
}

当我用实体B的有效实例手动设置“classB”属性,然后保存实体A的实例时,hibernate仍会尝试使用SELECT查询从数据库中检索“classB”属性,即使我手动加载了“classB”属性。

// Service Layer Code 
B classB = dao.getClassB();
A classA = new A();
classA.setClassB(classB);

// Dao function call will invoke hibernate session save() 
// this call will result in a SELECT query being made by hibernate
// to retrieve the instance of classB even though I just set it 
// in the previous line.
dao.save(classA);

为什么hibernate会这样做?有没有办法防止这种低效的查询发生?

0 个答案:

没有答案