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 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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With