JPA Inheritance

后端 未结 4 393
花落未央
花落未央 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 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.

提交回复
热议问题