0

oftentimes I have this kind of usage scenario:

entity A is connected to B through a 1--1 relation,

in code, I often simply use A.* and A.getB().getId(), I never use any other properties of B(), since the Id of B is actually stored in table A already, I do not necessarily have to load the B table, but hibernate always creates a JOIN or latter SELECT when it sees getB(). this is a huge problem if B table is big, or it has its own associations

is there a way to optimize for this special use case?

Thanks Yang

teddy teddy
  • 3,025
  • 6
  • 31
  • 48

2 Answers2

1

I don't think it's possible, because Hibernate doesn't know what the getId() method does: it might just return the ID (which is probably the case in 99% of the cases), but it could also transform it, has some side effects, log some message somewhere, whatever.

I'm not absolutely sure, but I think you might map the B_ID column in table A as a basic column (in addition to its mapping as a join column), provided you mark the column as non-insertable and non-updatable. If I'm correct, you could just call a.getBId() to get the ID of B without lazy-loading B.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thanks a lot, this way definitely works. I was also thinking along the line to do native sql, and assign the result to construct the B instance only partially, so that we do construct a B, but B only has its Id populated, the rest can be loaded on demand. I don't know what the syntax should be though. this way we don't need to change the mapping. maybe something like "select A.* , A.B_ID as {B.id} from A " ??? I'm pretty new to hibernate – teddy teddy Dec 15 '11 at 21:14
1

Hibernate one-to-one: getId() without fetching entire object

http://javaprogrammingtips4u.blogspot.com/2010/04/field-versus-property-access-in.html

basically you need to put the annotation on getId() instead of private Integer Id.

in terms of xml mapping file, you just need to put access="property" in the tag of your class

Community
  • 1
  • 1
teddy teddy
  • 3,025
  • 6
  • 31
  • 48