我试图将实体扩展为非实体,用于填充超类的字段.问题是,当我尝试保存它时,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);