Hibernate中的OneToOne关系映射---主键关联方式

主键关联不需要额外的表字段;如果两行是通过这种一对一关系相关联的,那么这两行就共享同样的主关键字值。
所以如果你希望两个对象通过主键一对一关联,你必须确认它们被赋予同样的标识值!

public class User {

    private String id;
    private String userName;
    private IDCard card;

    /**
     * @return the card
     */
    public IDCard getCard() {
        return card;
    }

    /**
     * @param card the card to set
     */
    public void setCard(IDCard card) {
        this.card = card;
    }

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

}
 
public class IDCard {

    private String id;
    private String cardNo;
    private User user;

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the cardNo
     */
    public String getCardNo() {
        return cardNo;
    }

    /**
     * @param cardNo the cardNo to set
     */
    public void setCardNo(String cardNo) {
        this.cardNo = cardNo;
    }

    /**
     * @return the user
     */
    public User getUser() {
        return user;
    }

    /**
     * @param user the user to set
     */
    public void setUser(User user) {
        this.user = user;
    }

}
 
<?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 >
	<class name="com.acca.entity.User" table="t_user"> 
		<id name="id">
		 <generator class="uuid"/>
		</id>
		<property name="userName"/>
		<one-to-one name="card" class="com.acca.entity.IDCard" cascade="all"/>
	</class>
</hibernate-mapping>
 
<?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 >
	<class name="com.acca.entity.IDCard" table="t_card"> 
		<id name="id">
		 <generator class="foreign">
              <param name="property">user</param>
          </generator>
		</id>
		<property name="cardNo"/>
		<one-to-one name="user" class="com.acca.entity.User"></one-to-one>
	</class>
</hibernate-mapping>

你可能感兴趣的:(Hibernate中的OneToOne关系映射---主键关联方式)