首页 > 代码库 > hibernate之12.many2many变形

hibernate之12.many2many变形

多对多关系中,中间表t_user_role不能添加额外的内容,如;创建时间,修改时间,操作员工员等等

我们可以通过另一种方式,多对一来解决.

首先来看一个类图,



图1:用户与角色关系



从图1中,我们发现: 

User类与UserRole类是 一对多关系,

Role类与UserRole也是一对多关系

通过UserRole类,我们可得到User类与Role类是多对多关系

CRUD:

UserRole

package com.demo.model;

import java.util.Set;

/**用户角色关系
 * @author wobendiankun
 *2014-11-6 下午10:33:34
 */
public class UserRole {
	private int userRoleId;
	private String operator;
	private User user;
	private Role role;
	
	public UserRole() {
	}
	public UserRole(String operator) {
		this.operator = operator;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public Role getRole() {
		return role;
	}
	public void setRole(Role role) {
		this.role = role;
	}
	public String getOperator() {
		return operator;
	}
	public void setOperator(String operator) {
		this.operator = operator;
	}
	public int getUserRoleId() {
		return userRoleId;
	}
	public void setUserRoleId(int userRoleId) {
		this.userRoleId = userRoleId;
	}
	
}

配置

<?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 >

	<class name="com.demo.model.UserRole" table="t_user_role">
		<id name="userRoleId" column="user_role_id">
			<generator class="sequence">
				<param name="sequence">SQE_T_USER_ROLE</param>
			</generator>
		</id>
		<property name="operator"/>
		<many-to-one name="user" column="user_id"></many-to-one>
		<many-to-one name="role" column="role_id"></many-to-one>
	</class>
</hibernate-mapping>

add:

package com.demo.model;

import org.hibernate.Session;
import org.junit.Test;

import com.demo.util.HibernateUtil;

/**多对多变形
 * @author wobendiankun
 *2014-11-6 下午10:42:34
 */
public class Many2ManyTransTest {
	@Test
	public void addTest(){
		UserRole userRole1=new UserRole("aa");
		userRole1.setUser(new User(61));
		userRole1.setRole(new Role(3));
		UserRole userRole2=new UserRole("bb");
		userRole2.setUser(new User(65));
		userRole2.setRole(new Role(3));
		
		Session session = null;
		try {
			session = HibernateUtil.openSession();
			session.beginTransaction();
			session.save(userRole1);
			session.save(userRole2);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		} finally {
			HibernateUtil.closeSession(session);
		}
	}
}

发出sql:

Hibernate: insert into t_user_role (operator, user_id, role_id, user_role_id) values (?, ?, ?, ?)
Hibernate: insert into t_user_role (operator, user_id, role_id, user_role_id) values (?, ?, ?, ?)


hibernate之12.many2many变形