Home > Net >  Java Hibernate INHERITANCE
Java Hibernate INHERITANCE

Time:01-27

Here is a basic drawing for my problem.

Description of my problem

So I have a Person class.

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "PERSON")
public class Person {
    @Id
    @Column(name = "person_id")
    @SequenceGenerator(sequenceName = "PERSON_ID_SEQ", allocationSize = 1, name="PERSON_ID_SEQ")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PERSON_ID_SEQ")
    private Long personId;
    
    private String name;
}

and for example a Police class that is inherited from a Person.

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "POLICE_MAN")
public class PoliceMan extends Person{
    @Id
    @Column(name = "police_id")
    private Long policeId;
    
    private String something;
}

So the problem is, I can't use @Id annotation in PoliceMan because I have one in the Person class. How could I solve that? How can a police_id be an uniqu identifier?

Thanks for help.

https://www.baeldung.com/hibernate-inheritance

I tried something from that page, but ...

CodePudding user response:

You missed the Inheritance mapping. Just extending the Person class is not a JPA inheritance. By looking at your code I suppose that you wanted to make a joined table inheritance, because you tried to map each entity to a different table.

To do so you have to use the @Inheritance(strategy = InheritanceType.JOINED) annotation on the PoliceMan class.

Also you should use the @PrimaryKeyJoinColumn(referencedColumnName = "person_id") annotation on the PoliceMan class. This indicates that the PK of the PoliceMan entity is person_id and it has a foreign key constraint to the PK of the Person. Remove the policeId field. With the annotations above you already have the person_id column in both of your tables (you don't have to declare an id in your PoliceMan class).

So if you do it manually on SQL side you have to create a person_id primary key column in PERSON table and also in POLICE_MAN table, and you should have a foreign key in POLICE_MAN table on person_id column that references the person_id column of the PERSON table.

CodePudding user response:

"It might be more accurate to associate it with a foreign key. You can establish a One To One relationship between Person and PoliceMan."

"our table structure doesn't show a FK from police->person. Nothing stops you from having a police_id attribute within your entity, it just can't be marked as THE id. You can have any number of unique identifiers within entities and tables - just mark the column with a uniqueness constraint. Plus one on this shouldn't be using inheritance despite that though. An officer (PoliceMan) is a role, not a defining characteristic of a person, and you'll have issues maintaining their existence as a person if it isn't separated out, just as you apparently are for the table data."

Thanks you all have right.

  • Related