JPA Inheritance

Hi, I'm new to JPA, and it's hard for me to understand how it handles inheritance.

I have a specific problem that I need to solve without changing the database schema, but if you cannot find a solution, I would appreciate a solution with a different database schema (we welcome Hibernate / TopLink solutions).

If I was unclear or if you need more information, please tell me about it. Thanks in advance!

I have this database:

TABLE Fruit
Id Varchar (10) Primary Key
size Varchar (10)
fruit_type Varchar(10)

TABLE Apple
Id Varchar (10) Primary Key Foreign Key references Fruit.Id
Apple_Property Varchar(10)

So far my objects look like this:

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="fruit_type", discriminatorType=DiscriminatorType.Char)
@DiscriminatorValue(value="fruit")

public class Fruit implements Serializable {

    @Id
    protected String Id;

    protected String size;
}

@Entity
@DiscriminatorValue(value="apple")
//@PrimaryKeyJoinColumn(name="Id" , referencedColumnName="Id")

public class Apple extends Fruit implements Serializable {

    private String Apple_Property;
}

Currently, I can save Fruit objects without any problems .. Apple objects are saved only when their Fruit object has not yet been saved.

If I try to save an Apple object with a Fruit object already saved:

Fruit fruit1 = new Fruit("1", "Small");
Apple apple1 = new Apple(fruit1, "red");
provider.create(fruit1);
provider.create(apple1);

I will get an error since JPA is trying to create a new row in the Fruit table with Id = "1" which already exists.

..

+3
4

JPA (.. provider.create(apple1) ) ​​ . , provider.create(apple1) Fruit Apple.

, Apple, provider.create(apple1). .

, FK Table PK @GeneratedValue Fruit bean. , java-, " " - java-.

+3

, , . Apple, JPA . JoinColumn .

+1

You are trying to use the concept of java inheritance when creating db tables, which is somewhat impossible in this case. I could think of one other approach to this problem. There is a table fruit_type and fruits. fruit_type (id, typename, desc) fruit (id, name, type_id, desc) here type_id will be the foreign key.

0
source

I have the same problem, and so far the only way I have found was to query the parent and build the child with the parent. Then delete the parent and recreate both records.

0
source

All Articles