简体   繁体   中英

Hibernate Annotations : No default constructor for entity

I am trying to persist the objects generated by JAXB. Here is the sample structure:

@Column(name = "reporting_identifier")
private String reportingIdentifier;
@Column(name = "apply_quiet_time")
private boolean applyQuietTime;
@Embedded
private RecipientDetailsList recipientDetailsList;

Below is the structure of RecipientDetailsList class:

@ElementCollection(targetClass=String.class)
private List<RecipientDetails> recipientDetails;

Now, the RecipientDetails class has one argument constructor, which accepts a String. That String I want to persist in the database as a part of the whole record. I am seeing

org.hibernate.InstantiationException: No default constructor for entity: RecipientDetailsList

exception when I try to save an object. I have two questions:

  1. Do we have any work around this exception? I can't change the class as it is designed for JAXB marshalling/unmarhsalling. Can I somehow store the objects without altering the structure? Also, I am interested in only storing the first record of the list referenced by recipientDetails as I want only one row for object. I want it to ignore the rest of the records if it has more than 1 record. Is it possible?

  2. Is this good design to use the annotation directly into classes which are generated by JAXB? Should I create another classes (and possibly mappers/converters) just to store and retrieve the information?

For your first question: this is happening because when Hibernate tries to create a bean, it does it via reflection. It does the object creation by calling the no-arg constructor, and then using the setter methods to set the properties. You can't use a bean that doesn't have a no-arg constructor.

For the second question: if something else has generated classes for you that don't have a no-arg constructor, really your only option (if you can't modify the class) is to create a wrapper round it, or a subclass that has a no-arg constructor. I don't see any other way of doing it if you can't modify the class directly. But the subclassing should be fine as long as the class you've got has enough visibility on the methods (ie, doesn't have private methods that you then can't get to).

If you mark RecipientDetails as @Embeddable hibernate will use the constructor with arguments.

@Embeddable
class RecipientDetails {

    //no default constructor

    public RecipientDetails(some arg) {}


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM