首页 > 代码库 > Hibernate学习8—Hibernate 映射关系
Hibernate学习8—Hibernate 映射关系
第一节:Hibernate 一对一映射关系实现
假设一个用户对应一个地址;
1)按照主键映射:
User.java:
package com.cy.model; public class User { private int id; private String name; private Address address; 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 Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
Address.java:
package com.cy.model; public class Address { private int id; private String address; private String zipcode; private User user; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
User.hbm.xml:
<hibernate-mapping package="com.cy.model"> <class name="User" table="t_user"> <id name="id" column="userId"> <generator class="native"></generator> </id> <property name="name" column="userName"></property> <one-to-one name="address" class="com.cy.model.Address" cascade="all"></one-to-one> </class> </hibernate-mapping>
Address.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.cy.model"> <!-- t_address表的主键和t_user表的主键一样; t_address表的id既做主键,又做外键。 --> <class name="Address" table="t_address"> <id name="id" column="addressId"> <generator class="foreign"> <param name="property">user</param> </generator> </id> <property name="address" column="address"></property> <property name="zipcode" column="zipcode"></property> <!-- 配置constrained="true"让t_address和t_user共享主键 --> <one-to-one name="user" class="com.cy.model.User" constrained="true"></one-to-one> </class> </hibernate-mapping>
测试代码:
@Test public void testSave1(){ User user=new User(); user.setName("张三"); Address address=new Address(); address.setAddress("昭潭镇"); address.setZipcode("247280"); address.setUser(user); user.setAddress(address); session.save(user); }
结果:
t_address表结构:
t_address表的addressId既是主键,又是外键;
执行结果,查看数据库:
2)按照外键映射
Hibernate学习8—Hibernate 映射关系
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。