’Caused by: java.sql.SQLException: 违反了 PRIMARY KEY 约束'PK_book',在Hi
点击右边红色标题查看本文完整版:’Caused by: java.sql.SQLException: 违反了 PRIMARY KEY 约束'PK_book',在Hibernate的TestUnit中插入对象时报错
使用Middlegen-Hibernate-r5,hbm2java.bat生成的.hbm.xml和Java文件
?
? 但在Hibernate的TestUnit中插入对象时报错:
? “Caused by: java.sql.SQLException: 违反了 PRIMARY KEY 约束'PK_book'。不能在对象 'book' 中插入重复键。”
?
? 下面是我的代码:
? /*
? * Created on 2005-3-20 dahe
? */
? package org.hibernate.sample;
?
? import java.util.List;
?
? import net.sf.hibernate.*;
? import junit.framework.*;
? import org.hibernate.sample.Book;
? import net.sf.hibernate.cfg.*;
?
? public class HibernateTest extends TestCase {
? Session session = null;
? protected void setUp() {
? try {
? Configuration config = new Configuration().configure();
? SessionFactory sessionFactory = config.buildSessionFactory();
? session = sessionFactory.openSession();
? } catch (HibernateException e) {
? e.printStackTrace();
? }
? }
?
? protected void tearDown() {
? try {
? session.close();
? } catch (HibernateException e) {
? e.printStackTrace();
? }
? }
?
? public void testInsert() {
? try {
? Book book = new Book();
? book.setBook("newbook"); //已经换了几次不同的名称,仍然说是重复插入
? book.setSn("aaa");
? Transaction tran=session.beginTransaction();
? session.save(book);
? tran.commit();
? } catch (HibernateException e) {
? e.printStackTrace();
? Assert.fail(e.getMessage());
? }
? }
?
? public void testSelect() {
? String hql = "FROM Book where book='Hibernate'";