这篇讲 基于主键的单向一对一关联映射
1.依然考察人和身份证的一对一关系,如果采用主键关联,那么其表结构应该为:
2.类结构
Person.java
public class Person implements Serializable{ private String id; private String name; private IdCard idCard; public Person() { } public Person(String name) { super(); this.name = name; } public String getId() { return id; } public void setId(String 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() { } 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. 映射文件
Person.hbm.xml
idCard
IdCard.hbm.xml
4.测试
public class HibernateTest { /** * 生成数据库表的工具方法 * */ @Test public void testCreateDB(){ Configuration cfg = new Configuration().configure(); SchemaExport se = new SchemaExport(cfg); //第一个参数 是否打印sql脚本 //第二个参数 是否将脚本导出到数据库中执行 se.create(true, true); } /** * 初始化表数据 */ @Test public 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(); } } /** */ @Test public void testGetData(){ Session session = HibernateUtil.getSession(); Person p1 = (Person)session.get(Person.class, "110086"); System.out.println(p1.getName()+"----"+p1.getIdCard().getId()+"----"+p1.getIdCard().getAddress()); HibernateUtil.close(); }}