Hibernate - Foreign keys instead of Entities

前端 未结 4 2099
名媛妹妹
名媛妹妹 2020-11-27 17:17

Currently, Hibernate allows me to load objects defined by *-to-one relationships directly with

entity1.getEntity2()

Is it possible to get

4条回答
  •  [愿得一人]
    2020-11-27 17:43

    Actually, it is default Hibernate behavior to only load the foreign key instead of the message object if the FetchType is LAZY. This is why there are proxies to the objects to be loaded when you specify LAZY FetchType.

    The foreign key is not visible directly, but it is of course the key of the object at the "one" end of the OneToMany relationship.

    However, with a field-based access type (e.g., in your case, where annotations are placed on fields), there is an unresolved hibernate issue: Hibernate loads the whole object behind the proxy from the database. ( http://blog.xebia.com/2009/06/13/jpa-implementation-patterns-field-access-vs-property-access/ )

    My concrete suggestion would be (as, for example, the "right" answer did not work in my case):

    • Use the message object directly, as Hibernate will only load it if non-foreign-key data is needed. Do not specify an additional field for the foreign key.
    • Switch the class to use property access, i.e. define getters and setters, and put your annotations from the fields to the getters.

提交回复
热议问题