问题
In my project I have a POJO called BaseEntity as shown below.
class BaseEntity{
private int id;
public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}
}
And a set of other POJO entity classes like Movie, Actor,...
class Movie extends BaseEntity{
private String name;
private int year;
private int durationMins;
//getters and setters
}
I'm using BaseEntity only for using it as a place holder in some interfaces. I never have to store a BaseEntity object. I have to store only the entity objects extended from BaseEntity. How should I annotate these classes so that I get one table per entity extended from the BaseEntity. For movie it should be like (id, name, year, durationMins).
回答1:
I found the answer in a totally unrelated post. I just have to annotate BaseEntity as @MappedSuperclass. The following code done what I needed.
@MappedSuperclass
class BaseEntity {
@Id
private int id;
//getters and setters.
}
@Entity
class Movie extends BaseEntity {
@Column
private String name;
@Column
private int year;
@Column
private int durationMins;
//getters and setters
}
回答2:
You can use @MappedSuperClass on your BaseEntity
, and have Movie
extend it.
@MappedSuperClass
class BaseEntity {
@Id
private int id;
...
}
class Movie extends BaseEntity {
...
}
回答3:
What you need is Table Per Concrete class strategy. And you do not need any annotation for your BaseEntity in this strategy. Have a look at this for more explanation.
来源:https://stackoverflow.com/questions/18764296/hibernate-annotation-using-base-entity