hibernate使用SchemaExport生成对应的数据库表

时间:2022-11-17 12:00:46

我们在项目中完成实体类和对应的*.hbm.xml配置文件后,可以使用junit4来生成对应的数据库表,具体如下:

新建一个hibernate项目,具体步骤,可以参见《Hibernate环境搭建和配置

项目架构如图:

hibernate使用SchemaExport生成对应的数据库表


Score实体类代码如下:

package com.robert.pojo;

public class Score {

private ScoreId scoreId ;
private double result ;//成绩
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
public ScoreId getScoreId() {
return scoreId;
}
public void setScoreId(ScoreId scoreId) {
this.scoreId = scoreId;
}


}



ScoreId实体类代码如下:

package com.robert.pojo;

import java.io.Serializable;

public class ScoreId implements Serializable{
private int stuId;// 学生编码
private int subjectId;// 科目编号

public int getStuId() {
return stuId;
}

public void setStuId(int stuId) {
this.stuId = stuId;
}

public int getSubjectId() {
return subjectId;
}

public void setSubjectId(int subjectId) {
this.subjectId = subjectId;
}

}

Score.hbm.xml配置如下:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.robert.pojo">
<class name="Score" table="score">
<!-- 联合主键 composite-id中的配置如下:
name:是class是Score中的主键,这里是:scoreId
class:是scoreId主键对应的联合主键的类,这里是ScoreId类
key-property:是联合主键所在的类ScoreId中的两个主键
-->
<composite-id name="scoreId" class="ScoreId">
<key-property name="stuId"></key-property>
<key-property name="subjectId"></key-property>
</composite-id>
<property name="result"></property>
</class>
</hibernate-mapping>

实体类Score.hbm.xml和实体类对应关系如图:


hibernate使用SchemaExport生成对应的数据库表


HibernateTest测试类的代码如下:

package com.robert.test;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class HibernateTest {

/**
* 根据*.hbm.xml文件对应的生成数据库表
*/
@Test
public void testCreateDB() {
Configuration cfg = new Configuration().configure() ;
SchemaExport se = new SchemaExport(cfg) ;
//第一个参数:是否生成ddl脚本
//第二个参数:是否执行到数据库中
se.create(true, true) ;
}


}

当我们使用junit4运行testCreateDB代码时,就会在数据库中生成对应的表,运行结果如图:

控制台打印的日志:

hibernate使用SchemaExport生成对应的数据库表


数据库生成的表结构:

hibernate使用SchemaExport生成对应的数据库表