Home > Back-end >  Hibernate - Extending Entities without a base table annotation?
Hibernate - Extending Entities without a base table annotation?

Time:12-22

I have the following 2 Hiberante entities:

Person

Animal 

They have the shared fields / columns e.g: name, age etc, however each primary key id field is named differently, e.g. there is person_id and animal_id

@Entity
@Table(name = "person")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person{
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonProperty
    @Column(name = "person_id")
    private Integer person_id;

    // all below fields are generic in all the entities
    @JsonProperty
    @Column(name = "name")
    private String name;

    @JsonProperty
    @Column(name = "age")
    private String age;

}

Is there a way that I can create a base entity super class that holds these generic name, age etc fields, then have Person, Animal and any new entities extend this super entity?

Note that the super class does not have a table of its own so I am not sure what I would have for the @Table value?

I also have the issue of the primary keys not all being named e.g. id so would have to specify them specifically in each entity.

CodePudding user response:

If you don't want to add a table in your database for this "super entity" (let's call the class Being), you can still make Person and Animal inherit from it (Person should inherit from Animal BTW), and do the mapping of the common fields on properties:

public abstract class Being {
    private Integer id;
    private String name;

    // ...

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //...
}

@Entity
@Table(name = "person")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person extends Being {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonProperty
    @Column(name = "person_id")
    public Integer getId() {
        return super.getId();
    }

    public void setId(Integer id) {
        super.setId(id);
    }

    // all below fields are generic in all the entities
    @JsonProperty
    @Column(name = "name")
    public String getName() {
        return super.getName();
    }

    public void setName(String name) {
        super.setName(name);
    }

    //...

}
  • Related