bezmax
bezmax

Reputation: 26142

Lazily loading an object in hibernate

Is there a way to load an object lazily (having only id loaded) with Hibernate?

I'm writing a synchronization code, which synchronizes a huge database. We are trying to do optimizations on it, and currently the bottleneck is hibernate loading lots of unneeded fields over a slow connection. For example:

Person p = createPersonFromOtherDbData(params);
Address a = loadAddressFromLocalDB(p.getAddressParams());
p.setAddress(a);
session.insert(p);

So basically, it would be enough to fetch an "id" of that "Address" object and put it into the new "Person" object. However, hibernate loads lots of unneeded fields (unneeded in the context of synchronization but needed in the rest of application) from Address object. Is there any way to optimize this part of code given that the session is stateless?

Adeed:

I believe this question is related to: Can I set an entity relation with just the ID? , however it also has no specific answer.

Upvotes: 1

Views: 94

Answers (2)

JB Nizet
JB Nizet

Reputation: 692151

Session.load() does exactly what you want, and is used mainly to implement your use-case: if the address is not loaded in the session cache yet, then it simply returns an Address proxy wrapping the id.

Upvotes: 2

Vimal Bera
Vimal Bera

Reputation: 10497

You can use projection to fetch particular field from the database. Here is one example :

List results = session.createCriteria(Employee.class)
    .setProjection( Property.forName("name"))
    .list();

Upvotes: 0

Related Questions