标签:name ati view session hiberna 外键 str 一对一 mod
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表结构:
2)按照外键映射
标签:name ati view session hiberna 外键 str 一对一 mod
原文地址:http://www.cnblogs.com/tenWood/p/7257252.html