1. 多对多的关联关系
1.1. 权限和用户是多对多的关联关系
权限类(对应表名: t_auth): 多方
角色类(对应表名: t_role): 多方
权限角色类(对应表名: t_auth_role): 中间表
1.2. 权限表
1.3. 角色表
1.4. 权限角色表
2. 多对多的关联关系例子
2.1. 创建一个名为spring-data-jpa-many2many的Java项目, 同时添加相关jar包, 并添加JUnit能力。
2.2. 新建Role.java
package com.bjbs.pojo;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity // 指定该类是实体类
@Table(name = "t_role") // 指定数据库表名(表名和实体类对应)
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@Id // 指定为主键
@GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主键生成策略
@Column(name = "id") // 指定表中列名(列名和属性名对应)
private Integer id;
@Column(name = "name")
private String name; // 角色名
// fetch=FetchType.EAGER立即加载
@ManyToMany(cascade=CascadeType.PERSIST, fetch=FetchType.EAGER)
// @JoinTable: 配置中间表信息
// joinColumns: 建立当前表在中间表中的外键字段
@JoinTable(name="t_auth_role", joinColumns=@JoinColumn(name="r_id"), inverseJoinColumns=@JoinColumn(name="a_id"))
private Set<Auth> auths = new HashSet<Auth>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Auth> getAuths() {
return auths;
}
public void setAuths(Set<Auth> auths) {
this.auths = auths;
}
@Override
public String toString() {
return "Role [id=" + id + ", name=" + name + "]";
}
}
2.3. 新建Auth.java
package com.bjbs.pojo;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity // 指定该类是实体类
@Table(name = "t_auth") // 指定数据库表名(表名和实体类对应)
public class Auth implements Serializable {
private static final long serialVersionUID = 1L;
@Id // 指定为主键
@GeneratedValue(strategy = GenerationType.IDENTITY) // 指定主键生成策略
@Column(name = "id") // 指定表中列名(列名和属性名对应)
private Integer id;
@Column(name = "name")
private String name; // 权限名
@ManyToMany(mappedBy="auths")
private Set<Role> roles = new HashSet<Role>();
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
@Override
public String toString() {
return "Auth [id=" + id + ", name=" + name + "]";
}
}
2.4. 新建RoleRepository.java
package com.bjbs.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.bjbs.pojo.Role;
/**
* 参数一T: 当前需要映射的实体; 参数二 T: 当前映射的实体中的id的类型
*/
public interface RoleRepository extends JpaRepository<Role, Integer> {
}
2.5. 新建TestRoleRepository.java
package com.bjbs.test;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.bjbs.dao.RoleRepository;
import com.bjbs.pojo.Role;
import com.bjbs.pojo.Auth;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestRoleRepository {
@Autowired
private RoleRepository roleRepository;
@Test
public void findOne() {
Role role = roleRepository.findOne(1);
System.out.println(role);
Set<Auth> auths = role.getAuths();
for (Auth auth : auths) {
System.out.println(auth);
}
}
@Test
public void save() {
// 创建角色
Role role = new Role();
role.setName("张三");
// 创建权限
Auth auth = new Auth();
auth.setName("注册用户");
// 建立关系
role.getAuths().add(auth);
auth.getRoles().add(role);
// 保存数据
roleRepository.save(role);
}
}
2.6. 在src下新建application.properties
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.25.138:3306/StudyMybatis?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=lyw123456
2.7. 在src下新建applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置读取properties文件的工具类 -->
<context:property-placeholder location="classpath:application.properties" />
<!-- 配置c3p0数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${spring.datasource.url}" />
<property name="driverClass" value="${spring.datasource.driverClassName}" />
<property name="user" value="${spring.datasource.username}" />
<property name="password" value="${spring.datasource.password}" />
</bean>
<!-- Spring整合JPA 配置EntityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- hibernate相关的属性的注入 -->
<!-- 配置数据库类型 -->
<property name="database" value="MYSQL" />
<!-- 正向工程 自动创建表 -->
<!-- <property name="generateDdl" value="true" /> -->
<!-- 显示执行的SQL -->
<property name="showSql" value="true" />
</bean>
</property>
<!-- 扫描实体的包 -->
<property name="packagesToScan">
<list>
<value>com.bjbs.pojo</value>
</list>
</property>
</bean>
<!-- 配置Hibernate的事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- 配置开启注解事务处理 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 配置springIOC的注解扫描 -->
<context:component-scan base-package="com.bjbs.service" />
<!-- Spring Data JPA 的配置 -->
<!-- base-package: 扫描dao接口所在的包 -->
<jpa:repositories base-package="com.bjbs.dao" />
</beans>
2.8. 查询角色
2.9. 保存角色