1

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.

Community
  • 1
  • 1
bezmax
  • 25,562
  • 10
  • 53
  • 84

2 Answers2

2

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • As I mentioned in my question, I'm operating over a StatelessSession object, which does not provide a `load` method. Could it be that given that the session is stateless, I can just put a `new Address(id)` and it will work? – bezmax Oct 29 '13 at 08:08
  • Sorry, I missed the part about the stateless session. I have no experience with them. What happens when you try? I would assume that it works, given that it does work with normal sessions. – JB Nizet Oct 29 '13 at 08:10
  • Ok, I have tried that (creating empty object with only id) and it does work. – bezmax Oct 30 '13 at 06:27
0

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();
Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
  • Yes I do, but the problem is that I can not use the fetched ID to create a relationship between newly created Person and old existing Address. – bezmax Oct 29 '13 at 08:00
  • Yeah true. That's because you did mention Address Field in your Person Table, not address_id. So hibernate is going to search for Address's object, not its id. Hope I cleary stated my point. – Vimal Bera Oct 29 '13 at 08:04