开发者

Hibernate & EntityManager with joins

开发者 https://www.devze.com 2023-01-26 19:03 出处:网络
In my hypothetical I have an annotated User model class. This User model also holds references to two sets:

In my hypothetical I have an annotated User model class. This User model also holds references to two sets:

  • A set of Pet objects (a开发者_开发知识库 Pet object is also an annotated model represented in the data layer)
  • A set of Food objects (a Pet object is also an annotated model represented in the data layer)

When I pull the User entity from the database (entityManager.find(User.class, id)) it will automatically fill all the User fields but it obviously wont fill the two sets.

Do I need to do entityManager.createQuery and just use a normal SQL join query then manually create the User object?

Thanks in advance


If you map your relations from User to Pet and Food using OneToMany you can chose whether to have the fields automatically collected or not.

See the API doc for javax.persistence OneToMany.

Depending on how you constructed the mapping (PK-FK or join tables etc), you may or may not get good performance with this. Having two OneToMany relations that are joined, means you may end up with a ridiculous amount of rows when you read up your user.


Mmm, No? That's probably not how you want to do it. I don't know why you say "it obviously won't fill the two sets." It's quite capable of filling in the sets for you, that's sort of the point behind using an ORM like hibernate in the first place. Your objects do what they look like they should in code and 'databasey' things are handled automatically as much as possible.

It is true that Hibernate will complain if you mark more than one collection as EAGER fetched, but it's not really clear you actually need either of them to be eager. Essentially once they are mapped, just accessing them causes the queries to be run to fill them in with data (assuming the Session is still open and so forth.) If you explain how you want it to work it would be easier to help with a solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号