sql语句:
/* 基于主键的映射 */
CREATE TABLE t_person_pk
(
id NUMBER(10) PRIMARY KEY,
name VARCHAR2(20) NOT NULL,
gender VARCHAR2(10),
age NUMBER(3) CHECK(age BETWEEN 1 AND 100)
);
CREATE TABLE t_passport_pk
(
id NUMBER(10) PRIMARY KEY REFERENCES t_person_pk(id),
bh VARCHAR2(20) NOT NULL UNIQUE
);
CREATE SEQUENCE t_person_pk_seq
START WITH 1
INCREMENT BY 1;
Person_PK.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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.iotek.basic.association.one2one.pojo">
<class name="Person" table="T_PERSON_PK">
<id name="id" column="ID" type="long">
<generator class="sequence">
<param name="sequence">t_person_fk_seq</param>
</generator>
</id>
<property name="name" type="string" column="NAME"/>
<property name="age" type="integer" column="AGE"/>
<property name="gender" type="string" column="GENDER"/>
<one-to-one name="passport" class="Passport" cascade="all"/>
</class>
</hibernate-mapping>
Passport_PK.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!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.iotek.basic.association.one2one.pojo">
<class name="Passport" table="T_PASSPORT_PK">
<id name="id" column="ID" type="long">
<generator class="foreign">
<param name="property">person</param>
</generator>
</id>
<property name="bh" type="string" column="BH"/>
<one-to-one name="person" class="Person"></one-to-one>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- property 元素用于配置Hibernate中的属性 键:值 -->
<!-- hibernate.connection.driver_class : 连接数据库的驱动 -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<!-- hibernate.connection.url : 连接数据库的地址,路径 -->
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<!-- hibernate.connection.username : 连接数据库的用户名 -->
<property name="connection.username">system</property>
<!-- hibernate.connection.password : 连接数据库的密码 -->
<property name="connection.password">root</property>
<!-- show_sql: 操作数据库时,会 向控制台打印sql语句 -->
<property name="show_sql">true</property>
<!-- 数据库方言配置 org.hibernate.dialect.Oracle10gDialect (选择最短的)-->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- 加载配置文件的pojo类,否则找不到,报错, unknow entity -->
<mapping resource="com/iotek/basic/pojo/Student.hbm.xml"/>
<mapping resource="com/iotek/basic/association/one2one/pojo/Passport_PK.hbm.xml"/>
<mapping resource="com/iotek/basic/association/one2one/pojo/Person_PK.hbm.xml"/>
</session-factory>
</hibernate-configuration>
无标题.png注意基于主键的关系映射和基于外键的关系映射之间,映射文件写法上的差异。
网友评论