问题描述
我正在尝试持久化 JAXB 生成的对象.这是示例结构:
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;
下面是RecipientDetailsList
类的结构:
@ElementCollection(targetClass=String.class)
private List<RecipientDetails> 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:没有实体的默认构造函数:RecipientDetailsList
org.hibernate.InstantiationException: No default constructor for entity: RecipientDetailsList
尝试保存对象时出现异常.我有两个问题:
exception when I try to save an object. I have two questions:
我们有解决这个异常的方法吗?我无法更改该类,因为它是为 JAXB 编组/解组而设计的.我可以在不改变结构的情况下以某种方式存储对象吗?另外,我有兴趣只存储引用的列表的第一条记录recipientDetails 因为我只想要一行对象.如果它有超过 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?
直接在 JAXB 生成的类中使用注解是不是很好?我是否应该创建另一个类(可能还有映射器/转换器)来存储和检索信息?
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?
推荐答案
对于你的第一个问题:这是因为当 Hibernate 尝试创建一个 bean 时,它通过反射来完成它.它通过调用无参数构造函数来创建对象,然后使用 setter 方法设置属性.您不能使用没有无参数构造函数的 bean.
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 (i.e., doesn't have private methods that you then can't get to).
这篇关于休眠注释:实体没有默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!