Hibernate 、多表关联映射-组件关联映射(component)

组件关联映射可以将一些简小的数据与主题放在一个表中,例如firstName 和LastName这两个结合在一起可以组成一个名字,但是再分别将这两个再建一个表就不太合适了,这个时候可以用到组件关联映射;

hibernate.cfg.xml:

<hibernate-configuration>
    <session-factory name="sessionFactory">
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    	<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    	<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8</property>
    	<property name="hibernate.connection.username">root</property>
    	<property name="hibernate.connection.password"></property>
    	<property name="hibernate.show_sql">true</property>
    	<property name="hibernate.format_sql">true</property>
    	<property name="hibernate.hbm2ddl.auto">update</property>
    	<mapping resource="cn/hbm/Person2.hbm.xml" />
    </session-factory>
</hibernate-configuration>

Person:

public class Person2 {
	private Integer id;
	private Name name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Name getName() {
		return name;
	}
	public void setName(Name name) {
		this.name = name;
	}
	
}
name:

public class Name {

	private String firstName;
	private String lastName;
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}	
}
hbm.xml

<hibernate-mapping package="cn.model">
	<class name="Person2" table="PERSON2">
		<id name="id" column="ID">
			<generator class="native"></generator>
		</id>
		<component name="name">
			<property name="firstName" column="FIRST_NAME" />
			<property name="lastName" column="LAST_NAME" />
		</component>
	</class> 
</hibernate-mapping>


	public void saveZujian(){
		Session session=null;
		Transaction tran=null;
		try{
			Person2 person=new Person2();
			Name name=new Name();
			name.setFirstName("jack");
			name.setLastName("tomson");
			person.setName(name);
			session=HibernateSessionFactory.getSession();
			tran=session.beginTransaction();
			session.save(person);
			tran.commit();
		}catch(Exception e){
			if(session!=null){
				session.close();
			}
		}
	}

执行保存以后可看到生成的SQL



确实创建在一张表中了。


执行查询:

public Person2 getPersonById(Integer id){
		Session session=null;
		try{
			session=HibernateSessionFactory.getSession();
			return (Person2)session.get(Person2.class, id);
		}catch(Exception e){
			if(session!=null){
				session.close();
			}
		}
		return null;
	}




posted @ 2015-10-26 17:33  Bodi  阅读(226)  评论(0编辑  收藏  举报