日期:2014-05-20  浏览次数:20743 次

用Junit测试hibernate的时候出现了一个异常
小弟想用往mysql中插入一条数据,由于该表不存在我把配置里面的property name="hbm2ddl.auto"设置成了create,那么当我建表的时候就应该在数据库中创建相应的表并插入数据。但是测试通不过,出现了如下异常:

测试方法:

public class TeacherTest {

private static SessionFactory sf=null;

@BeforeClass
public static void beforClass(){
sf = new Configuration().configure().buildSessionFactory();
}

@Test
public void testSave(){

Teacher t = new Teacher();
t.setTeacher_ID(1);
t.setTeacher_Age(1);
t.setTeacher_Name("1");
t.setTeacher_Title("1");

Session session = sf.openSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
session.close();
}

@AfterClass
public static void afterClass(){
sf.close();
}

}

实体类:
package model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="_Teacher")
public class Teacher {

private int teacher_ID;
private String teacher_Name;
private int teacher_Age;
private String teacher_Title;

@Id
public int getTeacher_ID() {
return teacher_ID;
}
public void setTeacher_ID(int teacher_ID) {
this.teacher_ID = teacher_ID;
}
public String getTeacher_Name() {
return teacher_Name;
}
public void setTeacher_Name(String teacher_Name) {
this.teacher_Name = teacher_Name;
}
public int getTeacher_Age() {
return teacher_Age;
}
public void setTeacher_Age(int teacher_Age) {
this.teacher_Age = teacher_Age;
}
public String getTeacher_Title() {
return teacher_Title;
}
public void setTeacher_Title(String teacher_Title) {
this.teacher_Title = teacher_Title;
}


}

配置文件:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

  <session-factory>

  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
  <property name="connection.username">root</property>
  <property name="connection.password">root</property>

  <!-- JDBC connection pool (use the built-in) -->
  <!-- <property name="connection.pool_size">1</property> -->

  <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

  <!-- Enable Hibernate's automatic session context management -->
  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache -->
  <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>
  <property name="format_sql">true</property>

  <!-- Drop and re-create the database schema on startup -->
  <!-- <property name="hbm2ddl.auto">create</property> -->