组成关系

在一个员工模型里面需要存入

员工公司所在地址的城市,街道

员工籍贯所在的城市,街道,

此时可以抽取城市,街道变成一个模型即是组成关系

Employee

public class Employee {
private Long id;
private String name;
// 公司的地址
private Address comAddress;
// 籍贯所在地
private Address homeAddress;

Employee.hbm.xml

<class name="Employee" table="t_employee">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<!-- 组成关系:以对象的方式来解决重复的信息 -->
<!-- 公司所在的地址 -->
<!-- class必须配置为全类名 -->
<component name="comAddress" class="Address">
<!-- property:name必须配置成java的属性,column配置成数据库的字段,而且不能重复 -->
<property name="city" column="com_city" />
<property name="street" column="com_street" />
</component>
<!-- 籍贯所在的地址 -->
<component name="homeAddress" class="Address">
<property name="city" column="home_city" />
<property name="street" column="home_street" />
</component>
</class>

MainTest

public class MainTest {
Session session = null; @Before
public void save() {
session = HibernateUtils.INSTANCE.getSession();
session.beginTransaction();
Address comAddress = new Address("bj", "st1");
Address homeAddress = new Address("sh", "st2"); Employee employee = new Employee("user");
employee.setComAddress(comAddress);
employee.setHomeAddress(homeAddress); session.save(employee);
} @Test
public void get() throws Exception {
Employee employee = (Employee) session.get(Employee.class, 1L);
System.out.println(employee);
System.out.println(employee.getComAddress());
System.out.println(employee.getHomeAddress());
} @After
public void colse() {
session.getTransaction().commit();
session.close();
}
}

源码地址

https://github.com/je-ge/hibernate

如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!

Hibernate 系列教程10-组成关系-LMLPHP

Hibernate 系列教程10-组成关系-LMLPHP

04-17 15:04