Java – how to persist entities from non entity subclasses in Hibernate
•
Java
I'm trying to extend an entity to a non entity to fill in the fields of the superclass The problem is that hibernate throws a mappingexception when I try to save it This is because even if I cast reportparser into report, the runtime instance is still 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 is only used to fill in fields
public class ReportParser extends report
{
public void setName(String htmlstring)
{
...
}
public void setValue(String htmlstring)
{
...
}
}
Try to convert 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);
I used this pattern before moving to ORM, but I can't figure out how to use hibernate Is it possible?
Solution
Is it absolutely necessary to subclass entities? You can 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);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
