gpt4 book ai didi

java - Hibernate:持久化对象

转载 作者:行者123 更新时间:2023-11-30 05:15:12 24 4
gpt4 key购买 nike

我正在尝试创建新的事件对象以通过 Hibernate 保存在数据库中。下面的代码成功创建了一个事件,但是当调用 session.save(evt) 时,我得到的返回值为 0(我认为这相当于 null)。谁能确定下面的问题是什么?如果您需要有关所涉及的类或 hibernate 映射文件的更多信息,请索取您需要的信息。

注意:假设数据库中存在事件表。

public class ScheduleUnitOfWork {
private Map<Service, Employee> assignments;
private Date startDate;
private Date endDate;
private String customerName;

public ScheduleUnitOfWork(Map<Service, Employee> assignments, Date startDate,
Date endDate, String customerName) {
super();

this.assignments = assignments;
this.startDate = startDate;
this.endDate = endDate;
this.customerName = customerName;
}

public boolean scheduleEmployees(){
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
Transaction tx = null;
boolean retVal = true;

try {
tx = session.beginTransaction();

for(Service s : assignments.keySet()){
Employee e = assignments.get(s);

Event evt = new Event();
evt.setAssignedService(s);
evt.setCustomerName(this.customerName);
evt.setEndDate(endDate);
evt.setStartDate(startDate);

System.out.println(session.save(evt));
}

tx.commit();

}catch(RuntimeException ex){
ex.printStackTrace();

if(tx != null){
tx.rollback();
}
session.close();

retVal = false;
}

return retVal;
}

}

<class name="Event" table="Events">
<id name="ID" column="ID" type="int">
<generator class="assigned"/>
</id>
<property name="startDate" column="startDate" type="timestamp"/>
<property name="endDate" column="endDate" type="timestamp"/>
<property name="customerName" column="customerName" type="string"/>
<many-to-one name="assignedService" column="serviceID"
class="org.hibernate.service.Service"
unique="true" not-null="true"/>

</class>

最佳答案

您的生成器类已“分配”,这意味着 Hibernate 将“按原样”获取 ID - 例如它会假设正在设置它。

看看various generator classes由 hibernate 支持。如果您希望自动生成 ID,最常见的方法是“身份”(如果您的数据库支持)或“序列”。

关于java - Hibernate:持久化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1695165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com