组合属性映射

来源:互联网 发布:克莱汤普森数据 编辑:程序博客网 时间:2024/06/05 10:40

如果持久化类的属性不是基本数据类型,也不是字符串、日期等标量类型的变量,而是一个复合类型的对象,这样的属性称为组件属性。例如,对Person类可能有个address属性,它的类型是Address。

Address类

package ComponentAttributeMapping;public class Address {private String city;private String street;private String zipcode;public Address() {// TODO Auto-generated constructor stub}public Address(String city, String street, String zipcode) {this.city = city;this.street = street;this.zipcode = zipcode;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getStreet() {return street;}public void setStreet(String street) {this.street = street;}public String getZipcode() {return zipcode;}public void setZipcode(String zipcode) {this.zipcode = zipcode;}}

Person类

package ComponentAttributeMapping;public class Person {private Long id;private String name;private int age;private Address address;public Person() {// TODO Auto-generated constructor stub}public Person(Long id, String name, int age, Address address) {super();this.id = id;this.name = name;this.age = age;this.address = address;}public Long getId() {return id;}public void setId(Long 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 Address getAddress() {return address;}public void setAddress(Address address) {this.address = address;}}

Person.hbm.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">    <hibernate-mapping package="ComponentAttributeMapping"> <class name="Person" table="person" ><id name="id" type="java.lang.Long" column="person_id"><generator class="identity"/></id><property name="name" type="string" column="person_name" length="20" /><property name="age" type="integer" column="person_age"/><!-- 组合属性映射 --><component name="address" class="Address" ><property name="city" /><property name="street" /><property name="zipcode" /></component></class></hibernate-mapping>

测试

package ComponentAttributeMapping;import org.hibernate.Session;import org.hibernate.Transaction;import util.HibernateUtil;public class test {public static void main(String[] args) {// TODO Auto-generated method stubSession session = HibernateUtil.getSession();Transaction tx = session.beginTransaction();Person person = new Person();Address address = new Address("北京","前门外大街15号","110011");person.setName("黄小明");person.setAge(20);person.setAddress(address);session.save(person);tx.commit();}}

结果


原创粉丝点击