Changing the type of an entity preserving its ID

前端 未结 5 1655
刺人心
刺人心 2020-12-31 11:07

I am using hibernate as a persistence layer. There are 2 entities that live in the same table extending one superclass with single table inheritance strategy.



        
5条回答
  •  借酒劲吻你
    2020-12-31 11:28

    Hibernate attempts to make persistence as transparent as it possibly can - which means it tries to follow the same principles as normal Java objects. Now, rephrasing your question in Java, you'd get:

    How can I convert an instance of B class into an instance of (incompatible) C class?

    And you know the answer to that - you can't. You can create a new instance of C and copy necessary attributes, but B will always be B, never C. Thus the answer to your original question is - it cannot be done via JPA or Hibernate API.

    However, unlike plain Java, with Hibernate you can cheat :-) InheritanceType.SINGLE_TABLE is mapped using @DiscriminatorColumn and in order to convert B into C you need to update its value from whatever's specified for B into whatever's specified for C. The trick is - you cannot do it using Hibernate API; you need to do it via plain SQL. You can, however, map this update statement as named SQL query and execute it using Hibernate facilities.

    The algorithm, therefore, is:

    1. Evict B from session if it's there (this is important)
    2. Execute your named query.
    3. Load what-is-now-known-as-C using former B's id.
    4. Update / set attributes as needed.
    5. Persist C

提交回复
热议问题