一、创建实体类
package com.wr.hibernate.entity; import java.util.HashSet; import java.util.Set; public class Person { private int id; private String name; private Set<Role> roles = new HashSet<Role>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } }
package com.wr.hibernate.entity; import java.util.HashSet; import java.util.Set; public class Role { private int id; private String name; private Set<Person> persons = new HashSet<Person>(); public Set<Person> getPersons() { return persons; } public void setPersons(Set<Person> persons) { this.persons = persons; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
二、创建POJO映射
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wr.hibernate.entity"> <class name="Person" table="person"> <id name="id" type="java.lang.Integer"> <column name="person_id" /> <!-- 指定主键的生成方式, native: 使用数据库本地方式 --> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="person_name" /> </property> <!-- 指定中间表person_role --> <set name="roles" table="person_role"> <key column="person_id"></key> <many-to-many class="Role" column="role_id"></many-to-many> </set> </class> </hibernate-mapping>
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.wr.hibernate.entity"> <class name="Role" table="role"> <id name="id" type="java.lang.Integer"> <column name="role_id" /> <!-- 指定主键的生成方式, native: 使用数据库本地方式 --> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="role_name" /> </property> <!-- 指定中间表person_role --> <set name="persons" table="person_role" inverse="true"> <key column="role_id"></key> <many-to-many class="Person" column="person_id"></many-to-many> </set> </class> </hibernate-mapping>