Idcard.hbm.xml:
Java code
<!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.xyy.domain.Idcard"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <generator class="foreign"> <param name="property">person</param> </generator> </id> <property name="validate" type="java.util.Date"> <column name="validate"/> </property> <!-- 配置one-to-one constrained:不配置,则不会自动生成外键列,配置了,则会生成外键列 --> <one-to-one name="person" constrained="true"/> </class> </hibernate-mapping>
Person.hbm.xml:
Java code
<!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.xyy.domain.Person"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <generator class="assigned"/> </id> <property name="name" type="java.lang.String"> <column name="name"/> </property> <!-- 配置one-to-one --> <one-to-one name="idcard" /> </class> </hibernate-mapping>
TestMain.java:
Java code
Person p1=new Person(); p1.setId(2); p1.setName("scott1"); Idcard idcard=new Idcard(); idcard.setValidate(new Date()); idcard.setPerson(p1); session.save(p1); session.save(idcard);
异常代码:
org.hibernate.exception.SQLGrammarException: Could not execute JDBC batch update
Caused by: java.sql.BatchUpdateException: ORA-00928: 缺失 SELECT 关键字 esc
<class name="com.xyy.domain.Idcard">
<class name="com.xyy.domain.Person">
都少了表名属性。
一对一映射默认使用cascade,可以不用显式配置。
一对一映射的外键很蛋疼……所以平常用多对一的特殊形式来进行关联。
采用<many-to-one>标签来映射,标签上设置unique属性,指定……
不用设置表名,会自动生成的