Hibernate 组件关联关系

实体关联的属性是个复杂类型的持久化类,但不是实体:数据库中没有表与该属性对应。需要将该属性的子属性保存到当前实体对应的表中。

Citizen类:
public class Citizen {
	private Integer id;
	private String name;
	private Address address;
	public Citizen() {
	}
	public Citizen(String name, Address address) {
		this.name = name;
		this.address = address;
	}
	// Getters and setters are omitted
}


Address类:
public class Address {
	private String province;
	private String city;
	private String district;
	public Address() {
	}
	public Address(String province, String city, String district) {
		this.province = province;
		this.city = city;
		this.district = district;
	}
	// Getters and setters are omitted
}


Citizen.hbm.xml:
<hibernate-mapping package="com.john.myhibernate.domain">
	<class name="Citizen" table="citizen">
		<id name="id">
			<generator class="native"/>
		</id>
		<property name="name" length="28" not-null="true" />
		<component name="address">
			<property name="province"/>
			<property name="city"/>
			<property name="district"/>
		</component>
	</class>
</hibernate-mapping>


测试保存:
public void testSave() {
	Session s = null;
	Transaction tx = null;
	
	Address address = new Address("Zhejiang", "Hangzhou", "Binjiang");
	Citizen citizen = new Citizen("Tremendously", address);
	
	try {
		s = HibernateUtil.getSession();
		tx = s.beginTransaction();
		s.save(citizen);
		tx.commit();
	} catch (HibernateException e) {
		if (tx != null)
			tx.rollback();
		e.printStackTrace();
	} finally {
		if (s != null)
			s.close();
	}
}


数据库记录:
id name         province city     district
  1 Tremendously Zhejiang Hangzhou Binjiang

你可能感兴趣的:(java,xml,Hibernate,component)