Hibernate JPA注解多对多


下面演示JPA注解方式的多对多关系映射。以用户 和 角色 为例。

更多多对多的需求可以参考XML版本的多对多映射:

http://www.yiidian.com/hibernate/hibernate-many2many.html

一、实体类

User:

/**
 * 用户(多方)
 * @author http://www.yiidian.com
 */
@Entity
@Table(name="t_user")
public class User implements Serializable{
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="id")
	private Integer id;
	@Column(name="user_name")
	private String userName;
	
	//关联角色
	@ManyToMany(targetEntity=User.class)
	//@JoinTable: 用于映射中间表
	//joinColumns: 当前方在中间表的外键字段名称
	//inverseJoinColumns:对方在中间表的外键字段名称
	@JoinTable(
			name="t_user_role",
			joinColumns=@JoinColumn(name="user_id"),
			inverseJoinColumns=@JoinColumn(name="role_id"))
	private Set<Role> roles = new HashSet<Role>();

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public Set<Role> getRoles() {
		return roles;
	}

	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}
	
	
}

Role:

/**
 * 角色(多方)
 * @author http://www.yiidian.com
 */
@Entity
@Table(name="t_role")
public class Role implements Serializable{
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="id")
	private Integer id;
	@Column(name="role_name")
	private String roleName;
	
	//关联用户
	@ManyToMany(targetEntity=User.class,mappedBy="roles")
	private Set<User> users = new HashSet<User>();

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getRoleName() {
		return roleName;
	}

	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	public Set<User> getUsers() {
		return users;
	}

	public void setUsers(Set<User> users) {
		this.users = users;
	}
	
}

二、配置hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
	
<hibernate-configuration>	
	<!-- 连接数据库的参数 -->
<session-factory>
	<!-- 1.连接数据库参数 -->
	<property name="hibernate.connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="hibernate.connection.url">
		jdbc:mysql://localhost:3306/hibernate
	</property>
	<property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password">root</property>

	<!-- 整合c3p0 -->
	<property name="hibernate.connection.provider_class">
		org.hibernate.c3p0.internal.C3P0ConnectionProvider
	</property>
	<!-- c3p0详细配置 -->
	<property name="c3p0.min_size">10</property>
	<property name="c3p0.max_size">20</property>

	<!-- hibernate方言 -->
	<property name="hibernate.dialect">
		org.hibernate.dialect.MySQLDialect
	</property>

	<!-- 2.hibernate扩展参数 -->
	<property name="hibernate.show_sql">true</property>
	<property name="hibernate.format_sql">true</property>
	<property name="hibernate.hbm2ddl.auto">update</property>

	<!-- 让session被TheadLocal管理 -->
	<property name="hibernate.current_session_context_class">
		thread
	</property>
	<property name="dialect"></property>
	<mapping class="com.yiidian.domain.Role" />
	<mapping class="com.yiidian.domain.User" />

</session-factory>
</hibernate-configuration>	

三、编写测试类

/**
 * 演示多对多的映射
 * @author http://www.yiidian.com
 */
public class Demo {
	
	@Test
	public void test1(){
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		
		User u1 = new User();
		u1.setUserName("小泽");
		
		User u2 = new User();
		u2.setUserName("小仓");
		
		Role r1 = new Role();
		r1.setRoleName("视觉总监");
		
		Role r2 = new Role();
		r2.setRoleName("动作指导");
		
		
		u1.getRoles().add(r1);
		r1.getUsers().add(u1);
		
		u2.getRoles().add(r2);
		r2.getUsers().add(u2);
		
		session.save(u1);
		session.save(u2);
		session.save(r1);
		session.save(r2);
		
		tx.commit();
	}
	
}

执行程序,控制台输出:

Hibernate: 
    insert 
    into
        t_user
        (user_name) 
    values
        (?)
Hibernate: 
    insert 
    into
        t_user
        (user_name) 
    values
        (?)
Hibernate: 
    insert 
    into
        t_role
        (role_name) 
    values
        (?)
Hibernate: 
    insert 
    into
        t_role
        (role_name) 
    values
        (?)
Hibernate: 
    insert 
    into
        t_user_role
        (user_id, role_id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        t_user_role
        (user_id, role_id) 
    values
        (?, ?)

一共生成三张表:

源码下载:https://pan.baidu.com/s/1eSbCeky