当我尝试通过hibernate持久层保存一些数据时出现异常,例外是
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): hbm.Employee
public void saveEmployee(Employee empValue) {
Session session = null;
Transaction tx = null;
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
Employee emp;
if (empValue.getEmpcode() != null) {
emp = (Employee) session.get(Employee.class, empValue.getEmpcode());
if (emp != null) {
System.out.println("Test");
emp.setEmpcode(empValue.getEmpcode());
emp.setDepartment(createDepartment("DEEE"));
emp.setEmpfname(empValue.getEmpfname());
emp.setEmplname(empValue.getEmplname());
emp.setEmpdob(empValue.getEmpdob());
emp.setEmpstatus(empValue.getEmpstatus());
emp.setEmptelno(empValue.getEmptelno());
emp.setAuditfield(empValue.getAuditfield());
session.update(emp);
}
} else
{
emp = new Employee();
emp.setEmpcode(empValue.getEmpcode());
emp.setDepartment(createDepartment("DEEE"));
emp.setEmpfname(empValue.getEmpfname());
emp.setEmplname(empValue.getEmplname());
emp.setEmpdob(empValue.getEmpdob());
emp.setEmpstatus(empValue.getEmpstatus());
emp.setEmptelno(empValue.getEmptelno());
emp.setAuditfield(empValue.getAuditfield());
session.save(emp);
}
tx.commit();
}
因为你可以看到课程在适当的地方被分配,我对异常感到困惑,期待一些帮助。
答案 0 :(得分:3)
Exception表示您没有为Employee类中标有@id的字段分配值。这个班级怎么样?您是否尝试通过其中一个提供的生成器生成Id值,还是要手动设置它们?
答案 1 :(得分:2)
异常消息ids for this class must be manually assigned before calling save()
是不言自明的。
这是因为您使用的是assigned
内置生成器。 assigned
生成器明确告诉Hibernate应用程序将分配标识符。来自5.1.4.1. Generator部分:
允许应用程序在调用
save()
之前为对象分配标识符。如果未指定<generator>
元素,则这是默认策略。
如果这不是您想要的,请使用其他生成器,例如native
(此
选择identity
,sequence
或hilo
,具体取决于底层数据库的功能:
<class name="LineItem" table="`Line Item`">
<id name="id" column="`Item Id`"/>
<generator class="native"/>
</id>
...
</class>
答案 2 :(得分:0)
使用以下类型的代码来保存员工 如果这没有用,请粘贴映射文件以了解字段empCode的详细信息。
helper = new HibernateHelper();
Customer custObject;
if (customer.getId() == 0) {
custObject = new Customer();
custObject.setCreatetimestamp(new Timestamp(System.currentTimeMillis()));
} else {
custObject = (Customer) helper.getSession().load(Customer.class, customer.getId());
}
custObject.setName(customer.getName());
custObject.setAddress(customer.getAddress());
custObject.setBillToAddress(customer.getBillToAddress());
custObject.setBillToPerson(customer.getBillToPerson());
custObject.setUpdatetimestamp(new Timestamp(System.currentTimeMillis()));
custObject.setEmail(customer.getEmail());
custObject.setDeleted(false);
Currency curr = (Currency) helper.getSession().load(Currency.class, x);
custObject.setCurrencyId(curr);
custId = (Long) helper.getSession().save(custObject);
helper.commit();