JPA 2.0: Load a subset of fields for an entity

前端 未结 3 983
太阳男子
太阳男子 2020-12-16 23:01

I have an Entity named address. The address Entity has several fields, one of which is CITY. I\'ve created a query by calling entityManager.createQuery but my query only inc

3条回答
  •  眼角桃花
    2020-12-16 23:47

    How would Hibernate load Address instances if you request for cities? JPA entities are objects, and objects are supposed to respect invariants. For example, one such invariant might be that an address always has an ID, a street, etc. If Hibernate loaded partial objects (with only the city attribute filled), those invariants would be broken and you could not rely on your own code anymore. You would also have all sorts of problems if you tried to attach such an Address to another object, or if you simply tried to remove it, because it wouldn't even has an ID anymore.

    So the short answer is no : it's not possible.

    The long answer is that since Adress is a POJO, you just have to create Addresses from the loaded cities by yourself, or by using a ResultTransformer. But you would get transient Address instances rather than attached Adress entities. This is a recipe for countless bugs and confusion, IMHO.

提交回复
热议问题