我正在尝试将实体扩展为用于填充超类字段的非实体。问题是,当我尝试保存它时,Hibernate会抛出MappingException。这是因为即使我将ReportParser强制转换为Report,但运行时实例仍然是ReportParser,因此Hibernate抱怨它是一个未知的实体。
@Entity @Table(name = "TB_Reports") public class Report { Long id; String name; String value; @Id @GeneratedValue @Column(name = "cReportID") public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name = "cCompanyName") public String getname() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "cCompanyValue") public String getValue() { return this.name; } public void setValue(String value) { this.value = value; } }
ReportParser仅用于填写字段。
public class ReportParser extends report { public void setName(String htmlstring) { ... } public void setValue(String htmlstring) { ... } }
尝试将其投射到报告中并保存
... ReportParser rp = new ReportParser(); rp.setName(unparsed_string); rp.setValue(unparsed_string); Report r = (Report)rp; this.dao.saveReport(r);
在转移到ORM之前,我已经使用了这种模式,但是我不知道如何使用Hibernate来实现。可能吗?
对实体进行子类化是否绝对必要?您可以使用构建器模式:
public class ReportBuilder { private Report report; public ReportBuilder() { this.report = new Report(); } public ReportBuilder setName(String unparsedString) { // do the parsing report.setName(parsedString); return this; } public ReportBuilder setValue(String unparsedString) { // do the parsing report.setValue(parsedString); return this; } public Report build() { return report; } } Report report = new ReportBuilder() .setName(unparsedString) .setValue(unparsedString) .build(); dao.saveReport(report);