Mark - 01 : 创建组合键的类
//必须实现Serializable这个接口
public class ScoreId implements Serializable {
private int stuId;//学生编号
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;
}
private int subjectId;//科目编号
}
Mark - 02 : 创建要映射的类
public class ScoreResult {
private ScoreId scoreId;//这也是一个类,将这个类作为主键
private Double result;//结果
public ScoreId getScoreId() {
return scoreId;
}
public void setScoreId(ScoreId scoreId) {
this.scoreId = scoreId;
}
public Double getResult() {
return result;
}
public void setResult(Double result) {
this.result = result;
}
}
Mark - 03 : 编写hbm文件和配置hibernate.cfg.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>
<!-- 普通配置这个要变成表的实体类 -->
<class name="com.hibernate.zujianhua.ScoreResult" table="ScoreResult">
<!-- 这个是配置组合主键,name是键名,class是类地址 -->
<composite-id name="scoreId" class="com.hibernate.zujianhua.ScoreId">
<!-- 这个是这个组合键类中所有的属性 -->
<key-property name="stuId"></key-property>
<key-property name="subjectId"></key-property>
</composite-id>
<!-- 实体类的属性 -->
<property name="result"/>
</class>
</hibernate-mapping>
#cfg:
<mapping resource="com/hibernate/zujianhua/ScoreResult.hbm.xml”/>
Mark - 04 : 生成数据库
public static void main(String[] args){
Configuration config = new Configuration().configure();
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure().build();
Metadata metadata = new MetadataSources(serviceRegistry)
.buildMetadata();
SchemaExport schemaExport = new SchemaExport();
schemaExport.create(EnumSet.of(TargetType.DATABASE), metadata);
}
网友评论