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 bef开发者_如何转开发ore 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);
You're not supposed to extend entity classes, unless to make more specialized entity classes. Entity-related annotations are retained in the subclass, thus Hibernate gets confused.
Putting business logic in entity classes is also highly debatable — you have to be aware that JPA implementors, like Hibernate, may (and usually do) run your getters/setters through generated proxies. With complicated logic inside you may come across problems that are difficult to trace.
精彩评论