简体   繁体   中英

Hibernate how to get by id from lazy object

I had entity A,A is many to one B,fetch type is lazy.

When i use below code B still lazy.

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;

how can i get 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); 

I think the access field and / or access type annotations can solve your problems

Source: http://256stuff.com/gray/docs/misc/hibernate_lazy_field_access_annotations.shtml

As you see from the above statement, this special handling of the getId() only works if you are mapping the object using property access type instead of field access. We use field access for all of our objects which allows us to better control the access to the fields of our classes instead of having set methods on everything. The trick is to define all of your fields with "field" access type but override and use "property" type just on the id field. You will need to add the @AccessType("property") annotation to the id field of your object and make sure you have a valid getId() and setId() methods. We are using package protected setId() calls for testing purposes -- using private may work if you want to restrict access more, 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
}

This will use the getId() and setId() accessors for the id but it will use the reflection fu to set the stuff field. Good stuff. Now when we call getId(), Hibernate knows that the method is the id accessor and allows it to be called directly without invoking the lazy object initializer which saves on a select. Obviously if you call getStuff() it will cause a select to lazy load in the stuff string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM