我有实体 A,A 是多对一 B,获取类型是惰性的。
当我使用下面的代码 B 时仍然很懒。
A a = session.get(A.class,aId);//a.getB(); is lazy
B b = session.get(B.class,bId);//this object is same whith a.getB();
//b.id is 0;
//b.name is null;
//b.age is 0;
//if i remove A a = session.get(A.class,aId);
//then
//b.id is bId;
//b.name is "Test";
//b.age = 18;
我怎样才能得到 don't empty B Use My code?
class A{
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="bId",nullable = false)
B b;
//getter and setter
}
class B{
@Column
int id;
@Column
String name;
@Column
int age;
//getter and setter
}
//it is in my porject,Shipment is A,OrderDetail is B
Shipment shipment = shipmentDao.getByDate(id, shipmentDate);
OrderDetail od = baseDao.getById(OrderDetail.class, id);
最佳答案
我觉得访问字段和/或访问类型注解可以解决你的问题
来源: http://256stuff.com/gray/docs/misc/hibernate_lazy_field_access_annotations.shtml
正如您从上面的语句中看到的,只有当您使用属性访问类型而不是字段访问来映射对象时,对 getId() 的这种特殊处理才有效。我们对所有对象都使用字段访问,这使我们能够更好地控制对类字段的访问,而不是对所有对象都设置方法。诀窍是使用“field”访问类型定义所有字段,但仅在 id 字段上覆盖和使用“property”类型。您需要将 @AccessType("property") 注释添加到对象的 id 字段,并确保您具有有效的 getId() 和 setId() 方法。我们正在使用包保护的 setId() 调用来进行测试——如果您想进一步限制访问,使用私有(private)可能会起作用,YMMV。
@Entity
public class Foo {
// the id field is set to be property accessed
@Id @GeneratedValue @AccessType("property")
private long id;
// other fields can use the field access type
@Column private String stuff;
public long getId() { return id; }
public void setId(long id) { this.id = id; }
String getStuff() { return stuff; }
// NOTE: we don't need a setStuff method
}
这将为 id 使用 getId() 和 setId() 访问器,但它将使用反射 fu 来设置 stuff 字段。好东西。现在,当我们调用 getId() 时,Hibernate 知道该方法是 id 访问器并允许直接调用它而无需调用节省选择的惰性对象初始化程序。显然,如果您调用 getStuff(),它将导致选择延迟加载到填充字符串中。
关于java - Hibernate如何从惰性对象中获取id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24073906/