这是我的类(class):
public class TrainLate {
private int id;
private Date startDate;
private Date endDate;
private Set<TrainSchedule> ts=new HashSet<TrainSchedule>();
public TrainLate(){}
public TrainLate(int id, Date startDate, Date endDate) {
super();
this.id = id;
this.startDate = startDate;
this.endDate = endDate;
}
// setters and getters...
}
日期类型是java.sql.Date
在另一个类中我使用 HQL:
String hql="SELECT new TrainLate(id,startDate,endDate) FROM TrainLate "+ "WHERE id="+String.valueOf(index);
其中 index 是一个 int 参数。
这是“TrainLate.hbm.xml”:
<class name="classes.TrainLate">
<id name="id">
<generator class="native"/>
</id>
<property name="startDate"/>
<property name="endDate"/>
<set name="ts" lazy="false" cascade="all-delete-orphan" inverse="true">
<key column="trainLateID" />
<one-to-many class="classes.TrainSchedule" />
</set>
</class>
异常(exception)情况:
Unable to locate appropriate constructor on class [classes.TrainLate] [SELECT new TrainLate(id,startDate,endDate) FROM classes.TrainLate WHERE id=0]
其中“classes”是包名。
最佳答案
首先:Hibernate 要求您的实体具有默认的无参数构造函数。
第二:你的 hql 应该是:"from TrainLate t where t.id = :id"
。
String hql = "from TrainLate t where t.id = :id";
List<TrainLate> result = (List<TrainLate>) session.createQuery(hql).setParameter("id", 1).list();
甚至更好。当您知道实体的 ID 时,您不需要使用 hql 进行搜索:
TrainLate t = session.get(TrainLate.class, 1L); // I assume your id is a Long
如果未找到实体,则返回 null
。
或
TrainLate t = session.load(TrainLate.class, 1L); // I assume your id is a Long
如果未找到实体,则抛出 ObjectNotFoundException
。
关于java - hibernate :无法在类上找到适当的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12363867/