学习点:
1 一对多映射,一方 Grade.hbm.xml的写法:
<hibernate-mapping>
<class name="com.ddwei.entity.Grade" table="grade">
<id name="gid" type="java.lang.Integer">
<column name="GID" />
<generator class="increment" />
</id>
<property name="gname" type="java.lang.String">
<column name="GNAME" length="20" not-null="true"/>
</property>
<!-- 配置单向的一对多关系 -->
<set name="students" table="student">
<!-- 指定的外键列 -->
<key column="gid">
</key>
<one-to-many class="com.ddwei.entity.Student"/>
</set>
</class>
</hibernate-mapping>
2 一对多映射,cfg.xml引入hbm路径方法
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/bendi?useUnicode=true&CharacterEncoding=utf8</property> <property name="connection.username">root</property> <property name="connection.password">***</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource = "com/ddwei/entity/Grade.hbm.xml"/> <mapping resource = "com/ddwei/entity/Student.hbm.xml"/> </session-factory> </hibernate-configuration>
3 一对多映射,一方java类引入多方方式
package com.ddwei.entity; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class Grade { private int gid; private String gname; private String gdesc; //在一方定义多方的集合 //一个班级有多个学生,且每个学生都是唯一的,所以用Set集合 private Set<Student> student = new HashSet<Student>(); public int getGid() { return gid; } public void setGid(int gid) { this.gid = gid; } public String getGname() { return gname; } public void setGname(String gname) { this.gname = gname; } public String getGdesc() { return gdesc; } public void setGdesc(String gdesc) { this.gdesc = gdesc; } public Set<Student> getStudent() { return student; } public void setStudent(Set<Student> student) { this.student = student; } public Grade(){ super(); } public Grade(int gid, String gname, String gdesc, Set<Student> student) { super(); this.gid = gid; this.gname = gname; this.gdesc = gdesc; this.student = student; } }
诸葛