日期:2014-05-16  浏览次数:20487 次

报错Could not execute JDBC batch update和java.sql.BatchUpdateException: Duplicate e
报错Could not execute JDBC batch update和java.sql.BatchUpdateException: Duplicate e
最近学hibernate,写了一段代码,第一次执行没问题,第二次执行报错了,想了一下,不应该是其他毛病,且报错是更新(update)出错,估计是第二次执行的时候刚好与第一次执行的结果出现了矛盾,于是去数据库将第一次执行的结果(主码)改了一下,再执行就不会报错了,呵呵(主要原因还是我在配置文件中对Department类和Employee类的id设置了唯一性)
package cn.itcast.hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;

import cn.itcast.hibernate.HibernateUtils;

import cn.itcast.hibernate.domain.Department;
import cn.itcast.hibernate.domain.Employee;

public class Many2One {

public static void main(String[] args){
add();
}


static Department add(){
Session s = null ;
Transaction tx = null;
try{
Department depart = new Department();
depart.setName("depart name");

Employee emp = new Employee();
emp.setDepart(depart);//因为这一行代码,将Employee和Department关联起来了
emp.setName("emp name");
s = HibernateUtils.getSession();
tx = s.beginTransaction();
s.save(depart);//先保存了depart
s.save(emp);//后保存emp,从而保证了emp中的Department不是空的
tx.commit();
return depart;
}finally{
if(s != null)
s.close();
}

}

}