Search code examples
javaoraclehibernatejpaintellij-idea

Java Hibernate INHERITANCE


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 ...


Solution

  • "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.