如何在 Hibernate 中持久化来自非实体子类的实体 [英] How to persist an entity from an non-entity subclass in Hibernate
问题描述
我正在尝试将一个实体扩展为一个用于填充超类字段的非实体.问题是当我尝试保存它时,Hibernate 会抛出一个 MappingException.这是因为即使我将 ReportParser 转换为 Report,运行时实例仍然是一个 ReportParser,因此 Hibernate 会抱怨它是一个未知实体.
I am trying to extend an entity into a non-entity which is used to fill the superclass's fields. The problem is that when I try to save it Hibernate throws a MappingException. This is because even though I cast ReportParser to Report, the runtime instance is still a ReportParser so Hibernate complains that it is an unknown entity.
@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 仅用于填写字段.
ReportParser is only used to fill in fields.
public class ReportParser extends report
{
public void setName(String htmlstring)
{
...
}
public void setValue(String htmlstring)
{
...
}
}
尝试将其转换为报告并保存
Attempt to cast it to a Report and save it
...
ReportParser rp = new ReportParser();
rp.setName(unparsed_string);
rp.setValue(unparsed_string);
Report r = (Report)rp;
this.dao.saveReport(r);
我在转向 ORM 之前使用过这种模式,但我不知道如何使用 Hibernate 来做到这一点.可能吗?
I've used this pattern before I moved to an ORM, but I can't figure out how to do this with Hibernate. Is it possible?
推荐答案
是否绝对有必要对实体进行子类化?您可以使用构建器模式:
Is it absolutely necessary to subclass the entity? You could use the builder pattern:
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);
这篇关于如何在 Hibernate 中持久化来自非实体子类的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!