jpa how to create new entity with same id as parent entity (JOINED Inheritance)

后端 未结 1 699
终归单人心
终归单人心 2021-01-22 06:44

my question is very similar to Changing the type of an entity preserving its ID, but instead i´m using InheritanceType.JOINED instead of Table_per_class.

This means i do

相关标签:
1条回答
  • 2021-01-22 07:07

    Just like in the question you've linked to, the answer is "you can't do this using Hibernate API".

    The reason is actually quite clear - Hibernate aims to make persistence as transparent as possible and, therefore, can't allow you do to things with persistent objects that you wouldn't be able to do with normal Java ones. Once you create an instance of Person (in plain java), it's always a Person. It will NEVER be a Doctor. The best you can do is to create a Doctor instance and copy Person's attributes to it.

    Unlike plain java, however, with Hibernate you can cheat and achieve what you want :-) but it has to be done via native SQL. In your method you'll need to:

    1. Evict Person instance from session (and 2nd level cache if applicable)
    2. Insert a row with matching ID (taken from Person instance) into Doctors table. That's the part that has to be done as native sql, but you can define it as named query and set the above id as parameter. Note that if have any constraints on Doctor properties, you'll need to make sure the values you insert satisfy them.
    3. Reload Person instance - which will now be loaded as Doctor.
    0 讨论(0)
提交回复
热议问题