person表中card_id 唯一,而且还有一个主键id,这就产生了数据冗余,事实上可以同时把主键id也作为外键,可以删除原有的外键card_id,也就是单向一对一的关联可以基于主键。
Person.java类
package com.org.model;
public class Person {
private int id;
private String name;
private Card card;
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;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
}
Card.java类
package com.org.model;
public class Card {
private int id;
private String cardNum;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCardNum() {
return cardNum;
}
public void setCardNum(String cardNum) {
this.cardNum = cardNum;
}
}
Person.hbm.xml映射文件
<?xml version="1.0"?> <!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.org.model"> <class name="Person" table="person"> <id name="id"> <generator class="foreign"> <param name="property">card</param> </generator> </id> <property name="name" column="name" not-null="true"/> <!-- constrained="true"表明该类主键由关联类生成 --> <one-to-one name="card" constrained="true"></one-to-one> </class> </hibernate-mapping>
Card.hbm.xml映射文件
<?xml version="1.0"?> <!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.org.model"> <class name="Card" table="card"> <id name="id"> <generator class="native"/> </id> <property name="cardNum" column="card_num" not-null="true"/> </class> </hibernate-mapping>
测试类:
package com.org.model.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.org.model.Card;
import com.org.model.Person;
import com.org.util.HibernateUtil;
public class HibernateTest1 {
@Test
public void testSave1() {
Session session = null;
Transaction tx = null;
try {
// 拿到session
session = HibernateUtil.getSession();
// 开启事务
tx = session.beginTransaction();
// 给实体赋值
Person person = new Person();
person.setName("aaa");
Card card = new Card();
card.setCardNum("11111111111111");
person.setCard(card);
session.save(person);
//提交事务
tx.commit();
} catch (Exception e) {
// 打印堆栈信息
e.printStackTrace();
// 事务回滚
if (tx != null) {
tx.rollback();
}
} finally {
HibernateUtil.closeSession(session);
}
}
}
结果:
Hibernate: insert into card (card_num) values (?)
Hibernate: insert into person (name, id) values (?, ?)