Spring Data JPA many to many

A user can have multiple roles.
A role can also have multiple users.
Users and roles are in a many-to-many relationship.

Table relationship establishment

User class

package domain;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "user")
public class User {
    
    

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private Long userId;
    @Column(name="user_name")
    private String userName;
    @Column(name="age")
    private Integer age;

    /**
     * 配置用户到角色的多对多关系
     *      配置多对多的映射关系
     *          1.声明表关系的配置
     *              @ManyToMany(targetEntity = Role.class)  //多对多
     *                  targetEntity:代表对方的实体类字节码
     *          2.配置中间表(包含两个外键)
     *                @JoinTable
     *                  name : 中间表的名称
     *                  joinColumns:配置当前对象在中间表的外键
     *                      @JoinColumn的数组
     *                          name:外键名
     *                          referencedColumnName:参照的主表的主键名
     *                  inverseJoinColumns:配置对方对象在中间表的外键
     */
    @ManyToMany(targetEntity = Role.class,cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinTable(name = "sys_user_role",
            //joinColumns,当前对象在中间表中的外键
            joinColumns = {
    
    @JoinColumn(name = "sys_user_id",referencedColumnName = "user_id")},
            //inverseJoinColumns,对方对象在中间表的外键
            inverseJoinColumns = {
    
    @JoinColumn(name = "sys_role_id",referencedColumnName = "role_id")}
    )
    private Set<Role> roles = new HashSet<Role>();

    public Long getUserId() {
    
    
        return userId;
    }

    public void setUserId(Long userId) {
    
    
        this.userId = userId;
    }

    public String getUserName() {
    
    
        return userName;
    }

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

    public Integer getAge() {
    
    
        return age;
    }

    public void setAge(Integer age) {
    
    
        this.age = age;
    }

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

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

    @Override
    public String toString() {
    
    
        return "User{" +
                "userId=" + userId +
                ", userName='" + userName + '\'' +
                ", age=" + age +
                '}';
    }
}

User Dao interface

package dao;

import domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface UserDao extends JpaRepository<User,Long> ,JpaSpecificationExecutor<User> {
    
    
}

Role class

package domain;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "role")
public class Role {
    
    

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "role_id")
    private Long roleId;
    @Column(name = "role_name")
    private String roleName;

    //配置多对多
    @ManyToMany(mappedBy = "roles",fetch = FetchType.EAGER)  //配置多表关系
    private Set<User> users = new HashSet<User>();

    public Long getRoleId() {
    
    
        return roleId;
    }

    public void setRoleId(Long roleId) {
    
    
        this.roleId = roleId;
    }

    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;
    }

    @Override
    public String toString() {
    
    
        return "Role{" +
                "roleId=" + roleId +
                ", roleName='" + roleName + '\'' +
                '}';
    }
}

Role Dao interface

package dao;

import domain.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface RoleDao extends JpaRepository<Role,Long> ,JpaSpecificationExecutor<Role> {
    
    
}

Explanation of mapping

@ManyToMany
Function: Used to map many-to-many relationships.
Attributes:
cascade: Configure cascade operations.
fetch: Whether the configuration uses lazy loading.
targetEntity: Configure the entity class of the target.

@JoinTable
Function: Configuration of the intermediate table.
Attributes:
nam: Configure the name of the intermediate table.
joinColumns: The foreign key field of the intermediate table is associated with the primary key field of the table corresponding to the current entity class.
inverseJoinColumn: The foreign key field of the intermediate table is associated with the primary key field of the opposite table.

@JoinColumn
role: used to define the correspondence between the primary key field and the foreign key field.
Attributes:
name: specify the name of the foreign key field
referencedColumnName: specify the name of the primary key field that references the main table
unique: whether it is unique. The default value is not unique
nullable: whether it is allowed to be null. The default value allows.
insertable: Whether to allow insertion. The default value allows.
updatable: Whether to allow updates. The default value allows.
columnDefinition: column definition information.

Configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/data/jpa
		http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

    <!--spring 和 spring data jpa的配置-->

    <!-- 创建entityManagerFactory对象交给spring容器管理-->
    <bean id="entityManagerFactoty" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--配置的扫描的包(实体类所在的包) -->
        <property name="packagesToScan" value="domain" />
        <!-- jpa的实现厂家 -->
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        </property>

        <!--jpa的供应商适配器 -->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!--配置是否自动创建数据库表 -->
                <property name="generateDdl" value="false" />
                <!--指定数据库类型 -->
                <property name="database" value="MYSQL" />
                <!--数据库方言:支持的特有语法 -->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
                <!--是否显示sql -->
                <property name="showSql" value="true" />
            </bean>
        </property>

        <!--jpa的方言 :高级的特性 -->
        <property name="jpaDialect" >
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>

        <!--注入jpa的配置信息
            加载jpa的基本配置信息和jpa实现方式(hibernate)的配置信息
            hibernate.hbm2ddl.auto : 自动创建数据库表
                create : 每次都会重新创建数据库表
                update:有表不会重新创建,没有表会重新创建表
        -->
        <property name="jpaProperties" >
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <!--创建数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root"></property>
        <property name="password" value="qwe123"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///jpa?useSSL=false&amp;serverTimezone=UTC" ></property>
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
    </bean>

    <!--整合spring dataJpa-->
    <jpa:repositories base-package="dao" transaction-manager-ref="transactionManager"
                   entity-manager-factory-ref="entityManagerFactoty" ></jpa:repositories>

    <!--配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactoty"></property>
    </bean>
    <!-- txAdvice-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- aop-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* dao.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>

    <context:component-scan base-package="dao,domain" ></context:component-scan>
</beans>

Many-to-many operation

Save

	@Test
    @Transactional
    @Rollback(false)
    public void  testCasCadeAdd() {
    
    
        User user = new User();
        user.setUserName("小王");
        user.setAge(19);
        Role role = new Role();
        role.setRoleName("java程序员");
        //配置用户到角色关系,可以对中间表中的数据进行维护   
        user.getRoles().add(role);
        //配置角色到用户的关系,可以对中间表的数据进行维护 
        role.getUsers().add(user);
        userDao.save(user);
    }

delete

	@Test
    @Transactional
    @Rollback(false)
    public void  testCasCadeRemove() {
    
    
        //查询1号用户
        User user = userDao.findOne(1l);
        //删除1号用户
        userDao.delete(user);
    }

Inquire

	@Test
    public void  testQuery() {
    
    
        User user = userDao.findOne(1l);
        System.out.println(user.getUserName());
        Set<Role> roles = user.getRoles();
        System.out.println(roles);
    }

Guess you like

Origin blog.csdn.net/weixin_42494845/article/details/108210826