Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Hibernate如何从惰性对象获取id_Java_Hibernate - Fatal编程技术网

Java Hibernate如何从惰性对象获取id

Java Hibernate如何从惰性对象获取id,java,hibernate,Java,Hibernate,我有实体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

我有实体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;
我怎样才能得到不为空的B使用我的代码

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); 

我认为访问字段和/或访问类型注释可以解决您的问题

资料来源:

从上面的语句中可以看到,只有在使用属性访问类型而不是字段访问来映射对象时,getId()的这种特殊处理才有效。我们对所有对象使用字段访问,这使我们能够更好地控制对类字段的访问,而不是对所有对象都设置方法。诀窍是使用“field”访问类型定义所有字段,但仅在id字段上重写并使用“property”类型。您需要将@AccessType(“property”)注释添加到对象的id字段中,并确保具有有效的getId()和setId()方法。我们使用包保护的setId()调用进行测试——如果您想进一步限制访问,那么使用private可能会起作用

@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访问器,并允许直接调用它,而无需调用保存在select上的惰性对象初始值设定项。显然,如果调用getStuff(),它将导致stuff字符串中的select延迟加载。

您可以发布模型类
a
B
它在我的项目中,代码是Shipping Shipping=ShippmentDao.getByDate(id,ShippmentDate);OrderDetail od=baseDao.getById(OrderDetail.class,id);装运为,订单详细信息已更新。答案请参见更新的答案