How to save an object from a subclass of non-entity in Hibernate

I am trying to extend an entity to a non-entity that is used to populate the fields of a superclass. The problem is that when I try to save it, Hibernate throws a MappingException. This is because, despite the fact that I passed ReportParser Report, the runtime instance is still ReportParser, so Hibernate complains that it is an unknown object.

@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 used only to fill in the fields.

 public class ReportParser extends report { public void setName(String htmlstring) { ... } public void setValue(String htmlstring) { ... } } 

Try to send it to the 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 template before I switched to ORM, but I cannot figure out how to do this with Hibernate. Is it possible?

+7
source share
2 answers

Do I need to subclass an entity at all? 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); 
+3
source

You should not extend entity classes unless you create more specialized entity classes. Annotations associated with an entity are stored in a subclass, so Hibernate gets confused.

Including business logic in entity classes is also highly controversial - you should be aware that JPA developers such as Hibernate can (and usually) run your receivers / setters through generated proxies. With complex logic inside, you may encounter difficulties that are difficult to track.

0
source

All Articles