Hibernate中的一对一映射

1.需求

  用户和身份证是一一对应的关系。

  有两种对应方式:

    用户id作为身份证表的外键,身份证号作为主键;

    用户id作为身份证表的主键;

2.实体Bean设计

  User:

public class User {
private int userId;
private String userName;
private IDCard idCard;
set...
get...
}

  IDCard(用户id作为外键):

public class IDCard {
private String cardNum;
private String place;
private User user;
set...
get...
}

  IDCard(用户id作为主键):

public class IDCard {
  //必须有此属性作为主键
private int userId;
private String cardNum;
private String place;
private User user;
set...
get...
}

3.配置映射文件

  user.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.juaner.hibernate.idcard">
<class name="User" table="t_usercard">
<id name="userId" column="u_id">
<generator class="native"/>
</id>
<property name="userName" column="u_name"/>
<!--一对一映射-->
<one-to-one name="idCard" class="IDCard"/>
</class> </hibernate-mapping>

  用户id作为外键:

<?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.juaner.hibernate.idcard">
<class name="IDCard" table="t_idcard" >
<id name="cardNum">
<!--允许赋值-->
<generator class="assigned"/>
</id>
<property name="place"/>
<!--一对一映射,有外键而且唯一-->
<many-to-one name="user" class="User" column="user_id" cascade="save-update" unique="true" />
</class> </hibernate-mapping>

  用户id作为主键:

<?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.juaner.hibernate.idcard">
<class name="IDCard" table="t_idcard" >
<id name="userId">
<!--主键生成方式是foreign,即把别的表的主键作为当前表的主键
property指定引用的对象,根据对象可以找到对象的类及映射文件,
从而找到表的主键
-->
<generator class="foreign">
<param name="property">user</param>
</generator>
</id>
<property name="cardNum"/>
<property name="place"/>
<!--基于主键的映射
constraint=true指定在主键上添加外键约束
-->
<one-to-one name="user" class="User" constrained="true" cascade="save-update" />
</class> </hibernate-mapping>
上一篇:浅谈MySQL集群高可用架构


下一篇:installing a 3D printer