您的位置:首页 > 数据库 > MySQL

用JUnit4自动生成Mysql的表,分别用xml与annotation方式

2011-11-11 20:03 246 查看
首先:在hibernate.cfg.xml中:

<mapping resource="com/mapping/msb/Student.hbm.xml"/>

<mapping class="com.mapping.msb.Teacher"/>

第二:做映射

xml映射:

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="com.mapping.msb.Student" table="student">

<id name="id">

<generator class="native"></generator>

</id>

<property name="name"></property>

</class>

</hibernate-mapping>

annotation映射:

@Entity

public class Teacher {

private int id;

private String name;

@Id

public int getId() {

return id;

}

……

第三:写Junit4文件

public class TestStudent {

public void testSchemaExport(){

//new SchemaExport(new Configuration().configure()).create(true, true);

new SchemaExport(new AnnotationConfiguration().configure()).create(true, true);

}

}

public class TestTeacher {

@Test

public void testSchemaExport(){

//new SchemaExport(new Configuration().configure()).create(true, true);

new SchemaExport(new AnnotationConfiguration().configure()).create(true, true);

}

}

测试成功

------------------------------------------------------------------Over---------------------------------------------------------------------------

注意以下几点:

1.如果忘了导入mysql的jar包,是不会报错的,但也不能建表。

2.当xml方式和ann方式都存在时,只能用AnnotationConfiguration()

3. 只要hibernate.cfg.xml中有,就会生成表

4.有时利用Myeclipse生成的java文件前面没有"+"号,也就是在JUnit4中不能测试单个@Test.

解决办法,调出OutLine窗口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: