在hibernate一對一實體映射中,常用有兩種方式,一種就是把一對一看作多對一的一個特例,即通過外鍵參考。
另一種是通過主鍵參考,限制兩個數據表中的主鍵使用相同的值。
po類
Person.java
- package po;
-
- public class Person {
- private int id;
- private String name; //姓名
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- }
Card.java
- package po;
-
- public class Card {
- private int id; //身份證ID
- private String number; //身份證號碼
- private Person person; //一個身份證號對應一個人
-
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getNumber() {
- return number;
- }
- public void setNumber(String number) {
- this.number = number;
- }
- public Person getPerson() {
- return person;
- }
- public void setPerson(Person person) {
- this.person = person;
- }
-
-
-
-
- }
Card.hbm.xml
- <hibernate-mapping>
- <class name="po.Card" table="card">
- <id name="id" type="integer">
- <generator class="native" />
- </id>
- <property name="number"></property>
- <!-- 是多對一的一種特例 unique=true設置為唯一關聯 -->
- <many-to-one name="person" unique="true" column="person"></many-to-one>
- </class>
- </hibernate-mapping>
Person.hbm.xml
- <hibernate-mapping>
- <class name="po.Person" table="person">
- <id name="id" type="integer">
- <generator class="native" />
- </id>
- <property name="name" />
-
- </class>
- </hibernate-mapping>
hibernate.cfg.xml
- <hibernate-configuration>
-
- <session-factory>
- <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
- <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
- <property name="connection.username">root</property>
- <property name="connection.password">1</property>
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="myeclipse.connection.profile">mysql</property>
- <property name="show_sql">true</property>
- <property name="format_sql">true</property>
- <mapping resource="po/Person.hbm.xml"/>
- <mapping resource="po/Card.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>