Environment set up
Source code address: gitee: gitee.com/ytfs-dtx/JP…
Import dependence
<properties>
<spring.version>5.2.5. RELEASE</spring.version>
<hibernate.version>5.4.10. The Final</hibernate.version>
<slf4j.version>1.7.30</slf4j.version>
<log4j.version>2.12.1</log4j.version>
<druid.version>1.1.21</druid.version>
<mysql.version>5.1.6</mysql.version>
</properties>
<dependencies>
<! -- spring beg -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<! Spring support for the ORM framework
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<! -- hibernate beg -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.2. The Final</version>
<exclusions>
<exclusion>
<artifactId>classmate</artifactId>
<groupId>com.fasterxml</groupId>
</exclusion>
</exclusions>
</dependency>
<! -- hibernate end -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<! -- Spring data jPA coordinates -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.6. RELEASE</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<! -- el beg using Spring data -->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>Copy the code
Creating a 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">
<! -- Configure entity class management factory -->
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<! -- Configure entity class scan -->
<property name="packagesToScan" value="xyz.ytfs.entity"/>
<! -- Configure jPA provider -->
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
<! Configure the provider's adapter -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<! -- Database type -->
<property name="database" value="MYSQL"/>
<! -- No automatic table creation -->
<property name="generateDdl" value="false"/>
<! -- Console print SQL statement -->
<property name="showSql" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQL55Dialect"/>
</bean>
</property>
<! Jpa dialect: Advanced features -->
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<! Configure JPA transaction manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean"/>
</bean>
<! -- JPA -->
<jpa:repositories base-package="xyz.ytfs.dao" transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactoryBean"/>
<! -- Configure data source -->
<context:property-placeholder location="classpath:jdbcConfig.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>Copy the code
Creating an entity Class
Note that
@manyTOMany Function: Used to map many-to-many relationship attributes: CASCADE: configures the cascading operation. Fetch: Configures whether lazy loading is used. TargetEntity: Entity class that configures the target. You don't have to write it when you map many-to-many. JoinTable Properties: nam: Specifies the name of the middle table. JoinColumns: Specifies the foreign key field of the middle table. InverseJoinColumn: Specifies the primary key field of the table corresponding to the current entity class. The foreign key field of the middle table is associated with the primary key field of the opposite table. @joinColumn Function: Defines the mapping between primary key fields and foreign key fields. Attribute: name: specifies the name of the foreign key field referencedColumnName: specifies the name of the primary key field referencing the primary table. Unique: Specifies whether the primary key field is unique. Default value not unique Nullable: specifies whether to allow nullable. Default value Yes. Insertable: Indicates whether the insertable is allowed. Default value Yes. Updatable: Indicates whether updates are allowed. Default value Yes. ColumnDefinition: specifies the columnDefinition.Copy the code
User
package xyz.ytfs.entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/ * * *@author by ytfs
* @Classname User
* @DescriptionTODO(user class) *@Date2020/5/9 company * /
@Entity
@Table(name = "sys_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long userId;
@Column(name = "user_name")
private String userName;
/** * Configure the many-to-many relationship between users and roles. * Configure the many-to-many mapping relationship. * 1. Declare the configuration of table relationships * *@ManyToMany(targetEntity = role.class) // Many-to-many * targetEntity: represents each other's entity class bytecode * 2. Configure the intermediate table (containing two foreign keys) *@JoinTableName: specifies the name of the intermediate table. * joinColumns: specifies the foreign key of the current object in the intermediate table@JoinColumnArray name: foreign key * referencedColumnName: primary key of the referenced primary table * inverseJoinColumns: foreign key of the configured peer object in the middle table */
@ManyToMany(targetEntity = Role.class, cascade = CascadeType.ALL)
@JoinTable(name = "sys_user_role".//joinColumns, foreign key of the current object in the middle table
joinColumns = {@JoinColumn(name = "sys_user_id", referencedColumnName = "user_id")},
//inverseJoinColumns, foreign key of the middle table
inverseJoinColumns = {@JoinColumn(name = "sys_role_id", referencedColumnName = "role_id")})
private Set<Role> roles = new HashSet<>();
public Long getUserId(a) {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName(a) {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Set<Role> getRoles(a) {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public String toString(a) {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\' ' +
", roles=" + roles +
'} '; }}Copy the code
Role
package xyz.ytfs.entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/ * * *@author by ytfs
* @Classname Role
* @DescriptionTODO(user type) *@Date2020/5/9 company * /
@Entity
@Table(name = "sys_role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_id")
private Long roleId;
@Column(name = "role_name")
private String roleName;
/** * Configure the many-to-many relationship between users and roles. * Configure the many-to-many mapping relationship. * 1. Declare the configuration of a table relationship *@ManyToMany(targetEntity = user.class) // Many-to-many * targetEntity: represents each other's entity class bytecode * 2. Configure the intermediate table (containing two foreign keys) *@JoinTable* name: specifies the name of the intermediate table. * joinColumns: specifies the foreign key of the current object in the intermediate table@JoinColumnArray * name: foreign key * referencedColumnName: primary key of the referenced primary table * inverseJoinColumns: foreign key of the configured peer object in the middle table */
/* @ManyToMany(targetEntity = User.class) @JoinTable(name = "sys_user_role", //joinColumns = {@joinColumns (name = "sys_role_id", referencedColumnName = "role_id")}, / / inverseJoinColumns, InverseJoinColumns = {@joinColumn (name = "sys_user_id", referencedColumnName = "user_id")})*/
@ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<>();
public Set<User> getUsers(a) {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Long getRoleId(a) {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public String getRoleName(a) {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Override
public String toString(a) {
return "Role{" +
"roleId=" + roleId +
", roleName='" + roleName + '\' ' +
", users=" + users +
'} '; }}Copy the code
Create an interface for the data access layer
IUserDao
package xyz.ytfs.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import xyz.ytfs.entity.User;
/ * * *@author by ytfs
* @Classname UserDao
* @DescriptionTODO(User's Data Access Layer interface) *@Date2020/5/10 0:05 * /
public interface IUserDao extends JpaRepository<User.Long>, JpaSpecificationExecutor<User> {}Copy the code
IRoleDao
package xyz.ytfs.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import xyz.ytfs.entity.Role;
/ * * *@author by ytfs
* @Classname IRoleDao
* @DescriptionTODO(user-specific job data access layer) *@Date2020/5/10 0:07 * /
public interface IRoleDao extends JpaRepository<Role.Long>, JpaSpecificationExecutor<Role> {}Copy the code
The test class
package xyz.ytfs.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import xyz.ytfs.dao.IRoleDao;
import xyz.ytfs.dao.IUserDao;
import xyz.ytfs.entity.Role;
import xyz.ytfs.entity.User;
import javax.transaction.Transactional;
import java.util.HashSet;
/ * * *@author by ytfs
* @Classname JpaManyToManyTest
* @DescriptionTODO(many-to-many test class) *@Date2020/5/10 0:08 * /
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class JpaManyToManyTest {
@Autowired
private IRoleDao roleDao;
@Autowired
private IUserDao userDao;
/** * Save a user, save a Role * * many-to-many Relinquish maintenance: the passive party (in this case, the selected party Role) relinquishes */
@Test
@Transactional
@Rollback(false)
public void testSave(a) {
User user = new User();
user.setUserName("Rain listens to the wind.");
Role role = new Role();
role.setRoleName("Program ape");
/* A many-to-many relationship in which both parties must abandon the maintenance of the intermediate table, otherwise an exception will be thrown */
role.getUsers().add(user);
user.getRoles().add(role);
this.userDao.save(user);
this.roleDao.save(role);
}
// Test cascading add (save a user and save the associated role of the user)
@Test
@Transactional
@Rollback(false)
public void testCasacdeSave(a) {
User user = new User();
user.setUserName("Rain listens to the wind.");
Role role = new Role();
role.setRoleName("Program ape");
/* to express a many-to-many relationship */
role.getUsers().add(user);
user.getRoles().add(role);
// Cascade operation, save the user at the same time save the user type
this.userDao.save(user);
}
/** * Cascading delete to delete customer */ whose ID is 1
@Test
@Transactional
@Rollback(false)
public void testDeleteCasaced(a) {
// Query user 1
User user = this.userDao.getOne(1L);
// Delete the user whose ID is 1 in cascade mode
this.userDao.delete(user); }}Copy the code