这篇讲解基于外键的一对一单向关联映射
1.考察如下信息,人和身份证之间是一个一对一的关系。表的设计
注意:基于外键的一对一关联的表结构和多对一的表结构是一致的,但是,外键是唯一的。
2.类的结构
Person.java
public class Person implements Serializable{private int id;private String name;private IdCard idCard;public Person() {}public Person(String name) {super();this.name = 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;}public IdCard getIdCard() {return idCard;}public void setIdCard(IdCard idCard) {this.idCard = idCard;} }
IdCard.java
public class IdCard implements Serializable{private String id;private String address;public IdCard() {// TODO Auto-generated constructor stub }public IdCard(String id, String address) {super();this.id = id;this.address = address;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}}
3.映射文件信息:
IdCard.hbm.xml
<hibernate-mapping package="cn.sxt.pojo"><class name="IdCard" table="t_idCard"><id name="id"><generator class="assigned"></generator></id><property name="address"/></class> </hibernate-mapping>
Person.hbm.xml
<hibernate-mapping package="cn.sxt.pojo"><class name="Person" table="t_person"><id name="id"><generator class="native"></generator></id><property name="name"/><!-- 基于外键的一对一和多对一的表结构是一样的,所以映射文件也一样,要保证外键是唯一的 --><many-to-one name="idCard" column="idCardId" unique="true"></many-to-one></class> </hibernate-mapping>
4.测试
public class HibernateTest {/*** 生成数据库表的工具方法* */@Testpublic void testCreateDB(){Configuration cfg = new Configuration().configure();SchemaExport se = new SchemaExport(cfg);//第一个参数 是否打印sql脚本//第二个参数 是否将脚本导出到数据库中执行se.create(true, true);}/*** 初始化表数据*/@Testpublic void testInit(){Session session = null;Transaction tx = null;try {session = HibernateUtil.getSession();tx = session.beginTransaction();IdCard card1 = new IdCard("110086", "湖北武当");IdCard card2 = new IdCard("110087", "光明顶");Person p1 = new Person("张三疯");p1.setIdCard(card1);Person p2 = new Person("殷素素");p2.setIdCard(card2);session.save(card1);session.save(card2);session.save(p1);session.save(p2);tx.commit();} catch (Exception e) {if(tx!=null)tx.rollback();}finally {HibernateUtil.close();}}/***/@Testpublic void testGetData(){Session session = HibernateUtil.getSession();Person p1 = (Person)session.get(Person.class, 1);System.out.println(p1.getName()+"----"+p1.getIdCard().getId()+"----"+p1.getIdCard().getAddress());HibernateUtil.close();} }