标签:one .hbm.xml 方法 property back str 映射文件 抛出异常 package
案例一:
public class Department { //公寓类,“一”方 private int id; private String name; //setter和getter方法.... }
public class Employee { //员工类,“多”方 ,既然是多对一,多方知道一放的信息,那么在多方中必须有一方的对象, private int id; private String name; private Department department; //setter和getter方法 }
Department.hbm.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 package="com.reiyen.hibernate.domain"> <class name="Department" > <id name="id" > <generator class="native" /> </id> <property name="name" /> </class> </hibernate-mapping>
Employee.hbm.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 package="com.reiyen.hibernate.domain"> <class name="Employee"> <id name="id"> <generator class="native" /> </id> <property name="name" /> <!-- name="department" name的值必须与Employee中的属性名一致. --> <many-to-one name="department" column="depart_id" class="Department" /> </class> </hibernate-mapping>
<many-to-one >元素建立了department属性和employee表的外键depart_id之间的映射.
name: 设定待映射的持久化类的属性名,此外为employee类的department属性.
column: 设定和持久化类的属性对应的表的外键,此外为employee表的外键depart_id.
class(可选):设定持久化类的属性的类型,此处设定department的类型是Department类.
not-null(可选):如果为true,表示department属性不能为null,该属性的默认值为false.当为true时,生成的employee表中depart_id外键会设置not-null约束,所以当Hibernate保存Employee对象时,会先检查它的department属性是否为null,如果为null,则会抛出异常.
标签:one .hbm.xml 方法 property back str 映射文件 抛出异常 package
原文地址:http://www.cnblogs.com/shyroke/p/6853033.html