JPA Inheritance

后端 未结 4 391
花落未央
花落未央 2021-01-14 17:11

Hi I\'m new to JPA and I\'m having trouble understanding how it handles inheritance.

I have a specific problem I need solved without changing the DB scheme, but if y

相关标签:
4条回答
  • 2021-01-14 17:53

    You are trying to use java inheritance concept while creating the db tables, which is somewhat not possible in this case. I could think one different approach for this problem. Have table fruit_type and fruit. fruit_type(id, typename,desc) fruit(id, name, type_id, desc) here type_id will be the foreign key.

    0 讨论(0)
  • 2021-01-14 18:00

    I think this is working exactly as designed. When you use joined inheritance and persist an apple object, JPA will automatically insert into both the apple and fruit tables. You don't need to model an additional relation or JoinColumn in your entity classes.

    0 讨论(0)
  • 2021-01-14 18:03

    I have the same issue and so far the only way I found was to query the parent and construct child with parent. Then remove parent and recreate both records.

    0 讨论(0)
  • 2021-01-14 18:10

    When using JPA to persist a child object (i.e provider.create(apple1) in your case) , a record will be inserted to the child table and all of its parent tables. So provider.create(apple1) will insert a record to the Fruit and a record to the Apple table.

    In your example , if you only want to persist an apple object ,just call provider.create(apple1) is enough . It will persist the fruit reference inside the apple object too.

    BTW , I suggest the Fruit Table 's PK to be a number type , and uses @GeneratedValue to mark the ID field of the Fruit bean. In this way , you can let the database to generate an ID for you and no longer need to set it explicitly in the java code to avoid this "ID already exist error" because of setting an already existing ID in the java code.

    0 讨论(0)
提交回复
热议问题