hibernate 关联映射(2)

这里紧接着上一遍文章

新建一个Person类

package com.nerd.entity;

import java.util.HashSet;
import java.util.Set;

public class Person {
	public Set getEvents() {
		return events;
	}


	public void setEvents(Set events) {
		this.events = events;
	}
	private Set events = new HashSet();

	

	private long id;
	private int age;
	private String firstname;
	private String lastname;
	public Person() {

	}
	
	
	public int getAge() {
		return age;
	}
	public String getFirstname() {
		return firstname;
	}
	public long getId() {
		return id;
	}
	public String getLastname() {
		return lastname;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
	public void setId(long id) {
		this.id = id;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
}
2:创建映射文件

<?xml version="1.0" encoding='UTF-8'?> 

<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
 <hibernate-mapping>
 	<class name="com.nerd.entity.Person" table="person">
 		<id name="id" type="long" column="PERSON_ID">
 			<generator class="native" />
 		</id>
 		<property name="age" />
 		<property name="firstname" />
 		<property name="lastname" />
 		<set name="events" table="person_event">
 			<key column="PERSON_ID" />
 			<many-to-many column="EVENT_ID" class="com.nerd.entity.Event" />
 		</set>
 	</class>
 </hibernate-mapping>

3:把配置加入到hibernate.cfg.xml中

<mapping resource="com/nerd/entity/Person.hbm.xml"/>

4:创建一个方法使关联工作

private void creatAndStorePerson(String firstname,String lastname){
		Session session = HibernateUtil.getsSessionFactory().getCurrentSession();
		session.beginTransaction();
		Person person = new Person();
		person.setId(1234l);
		person.setAge(12);
		person.setFirstname(firstname);
		person.setLastname(lastname);
		session.save(person);
		session.getTransaction().commit();
	}
	
	private void addPersonToEvent(long personid,long eventid){
		Session session = HibernateUtil.getsSessionFactory().getCurrentSession();
		session.beginTransaction();
		Person aPerson = (Person)session.load(Person.class, personid);
		Event aEvent = (Event)session.load(Event.class, eventid);
		aPerson.getEvents().add(aEvent);
		session.getTransaction().commit();
	}


注意Hibernate的generator属性使用,如果使用native为主键自动生成策略,由底层方言实现,
要想自己设置数据持久化到数据库,需要使用assigned(用户自定义id)


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。