IdCard.java类
public class IdCard { private int id; private String cardNo; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCardNo() { return cardNo; } public void setCardNo(String cardNo) { this.cardNo = cardNo; } }
Person.java类
public class Person { private int id; private String name; private IdCard idCard; 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 IdCard getIdCard() { return idCard; } public void setIdCard(IdCard idCard) { this.idCard = idCard; } }
IdCard.hbm.xml映射文件
<?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.hibernate.IdCard" table="t_idCard"> <id name="id"> <generator class="native"> </generator> </id> <property name="cardNo"/> </class> </hibernate-mapping>
Person.hbm.xml映射文件
<?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.bjpowernode.hibernate.Person" table="t_person"> <id name="id"> <generator class="native"> <!-- property只关联对象 --> <param name="property">idCard</param> </generator> </id> <property name="name"/> <many-to-one name="idCard" unique="true"/> </class> </hibernate-mapping>
hibernate.cfg.xml配置文件
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_one2one_ufk</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <mapping resource="com/hibernate/Person.hbm.xml"/> <mapping resource="com/hibernate/IdCard.hbm.xml"/> </session-factory> </hibernate-configuration>
One2OneTest.java测试类(里面用到的工具类前面的博客中已经给出)
public void testSave1(){ Session session = null; try{ session = HibernateUtils.getSession(); session.beginTransaction(); IdCard idCard = new IdCard(); idCard.setCardNo("1111111111111111111"); session.save(idCard); Person person = new Person(); person.setName("张三"); person.setIdCard(idCard); session.save(person); session.getTransaction().commit(); }catch(Exception e){ e.printStackTrace(); session.getTransaction().rollback(); }finally{ HibernateUtils.closeSession(session); } }
测试结果(发出的sql语句):
Hibernate: insert into t_idCard (cardNo) values (?) Hibernate: insert into t_person (name, idCard) values (?, ?)