首页 > 代码库 > hibernate 之 关联映射的基于外键的单向一对一映射
hibernate 之 关联映射的基于外键的单向一对一映射
1. 人和身份证是一个一对一的关系,他们的表结构为:
2. 类结构:IdCard.java :
public class IdCard { 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; } }
person.java :
public class Person { private int id; private String name; private int age; private IdCard idCard; public Person() { } public Person(String name, int age) { super(); this.name = name; this.age = age; } 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public IdCard getIdCard() { return idCard; } public void setIdCard(IdCard idCard) { this.idCard = idCard; } }
3. 映射文件:IdCard.hbm.xml :
<hibernate-mapping> <class name="cn.wh.vo.IdCard" table="t_idCard"> <id name="id"> <generator class="assigned"></generator> </id> <property name="address"/> </class> </hibernate-mapping>
Person.hbm.xml :
<hibernate-mapping> <class name="cn.wh.vo.Person" table="t_person"> <id name="id"> <generator class="native"></generator> </id> <property name="name"/> <property name="age"/> <!-- 配置基于外键的一对一的关联映射 和多对一映射几乎一致,需要设置unique=true --> <many-to-one name="idCard" column="idCardId" unique="true"/> </class> </hibernate-mapping>
4. 测试:
public class HibernateTest { private Session session=null; @Before public void setUp(){ session = HibernateUtil.getSession(); } @After public void tearDown(){ HibernateUtil.close(); } @Test public void testCreateDB(){ Configuration cfg = new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); //第一个参数 是否打印 数据库脚本 //第二个参数 是否将脚本导入数据库执行 export.create(true, true); } @Test public void testInit(){ Transaction tx = null; try { tx = session.beginTransaction(); IdCard card1 = new IdCard("1101","北京昌平"); IdCard card2 = new IdCard("1102", "北京海淀"); Person p1 = new Person("张三",22); p1.setIdCard(card1); Person p2 = new Person("李四",23); 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(); } } @Test public void testGet(){ Person p1 = (Person)session.get(Person.class, 1); System.out.println(p1.getName()+"---"+p1.getAge()+"----"+p1.getIdCard().getAddress()); } }
hibernate 之 关联映射的基于外键的单向一对一映射
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。