我能够像本教程中那样使用SINGLE_TABLE继承策略将模型与实体映射https://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/Inheritance#Avoiding_Inheritance
基类初始化很好,但是当我尝试访问最派生的零件属性时,会得到空值。
因为我是EcpliseLink / Hibernate的初学者,所以我认为问题出在映射中。
基础类
@Entity
@Table(name="event")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "EVENT_TYPE")
public abstract class Events implements Serializable {
public Events(){
}
public Events(java.sql.Date date, int totalPlaces, int availablePlaces, String shortDescription,
String longDescription) {
Date = date;
TotalPlaces = totalPlaces;
AvailablePlaces = availablePlaces;
ShortDescription = shortDescription;
LongDescription = longDescription;
this.location = location;
this.picture = picture;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected int Id;
@Basic(optional=false)
protected Date Date;
@Basic(optional=false)
protected String Company;
@Basic(optional=false)
protected int TotalPlaces;
@Basic(optional=false)
protected int AvailablePlaces;
@Column(nullable = true, name="ShortDescription")
protected String ShortDescription;
@Column(nullable = true, name="LongDescription")
protected String LongDescription;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn(name="Id")
protected Location location;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn(name="Id")
protected Pictures picture;
abstract public String getCompany() {
return "Hochschule";
}
public void setCompany(String company) {
//
}
abstract public Double getPrice();
public void setPrice(Double price) {
//
}
abstract public void identify();
//gtrs strs
派生部分
@Entity
@DiscriminatorValue(value="EXCURSION")
public class Excursion extends Events {
public Excursion(){
}
public Excursion(java.sql.Date date, Double price, int totalPlaces, int availablePlaces, String shortDescription, String longDescription) {
super(date, totalPlaces, availablePlaces, shortDescription, longDescription);
this.Price = price;
}
@Basic(optional=false)
private Double Price;
@Override
public Double getPrice() {
System.out.println("Derived Part getPrice called ");
return Price;
}
@Override
public String getCompany(){
return "Hochschule Ulm";
}
@Override
public void setPrice(Double price) {
Price = price;
}
@Override
public void identify(){
System.out.println("This is Excursion");
}
}
Main
List<Events> ls = em.createNamedQuery("Events.findAllEvents").getResultList();
for(Events e : ls){
e.identify();
System.out.println(e.getId()+" "+e.getPrice());
// getPrice() returns null for every record
}
}
List<Excursion> le = em.createNamedQuery("Excursion.findAllExcursions").getResultList();
List<CompanyExcursion> lc = em.createNamedQuery("CompanyExcursion.findAllExcursions").getResultList();
List<Events> ls = new ArrayList<>();
ls.addAll(le);
ls.addAll(lc);