![](https://i-blog.csdnimg.cn/blog_migrate/a26f52b7f01b5a7c3717e7b55f8b89a6.png)
pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.spring_mybatis</groupId>
<artifactId>spring_mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<!-- Spring版本号 -->
<spring.version>5.1.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring core 核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring bean bean的管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring Aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring context support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring El表达式 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>
User实体类
package com.spring_mybatis.entity;
import java.util.List;
public class User {
private int id;
private String username;
private String password;
private String phone;
private String nickname;
private String email;
private List<Role> roles; // 角色列表
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", phone=" + phone
+ ", nickname=" + nickname + ", email=" + email + ", roles=" + roles + "]";
}
}
Role实体类
package com.spring_mybatis.entity;
public class Role {
private int role_id;
private String role_name; // 角色名字
private String role_description; // 角色描述
public Role() {
super();
}
public int getRole_id() {
return role_id;
}
public void setRole_id(int role_id) {
this.role_id = role_id;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
public String getRole_description() {
return role_description;
}
public void setRole_description(String role_description) {
this.role_description = role_description;
}
@Override
public String toString() {
return "Role [role_id=" + role_id + ", role_name=" + role_name + ", role_description=" + role_description + "]";
}
}
jdbc.properties配置文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_spring_mybatis
jdbc.username=root
jdbc.password=root
mybatis-config.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 自动配置类的别名 -->
<typeAliases>
<package name="com.spring_mybatis.entity" />
</typeAliases>
</configuration>
spring-mybatis.xml配置文件
<?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:tx="http://www.springframework.org/schema/tx"
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-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 读取数据库连接的配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 创建数据源,连接数据库 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<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>
<!-- 创建sqlSessionFactory工厂,在工厂中依赖数据源,将数据源映射到sqlSessionFactory中 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 获得mybatis-config.xml配置文件的别名配置 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 别名配置,不用mybatis-config.xml配置文件的别名配置 -->
<!-- <property name="typeAliasesPackage" value="com.spring_mybatis.entity"/> -->
<!-- ref中的dataSource是<bean id="dataSource">创建数据源,连接数据库的id值 -->
<property name="dataSource" ref="dataSource" />
<!-- 获得所有的mapper文件,自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:mappers/*.xml" />
</bean>
<!-- 配置dao接口所在的包。DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 得到所有的dao接口文件,与mapper文件进行对应的映射 -->
<property name="basePackage" value="com.spring_mybatis.dao" />
<!-- 依赖sqlSessionFactory工厂 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 事务管理器(由Spring管理MyBatis的事务) -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 关联数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
spring-beans.xml配置文件
<?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:tx="http://www.springframework.org/schema/tx"
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-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 开启组件扫描,自动扫描包,base-package="com.spring_mybatis"的作用就是找到基础包下面的所有类进行注入 -->
<context:component-scan base-package="com.spring_mybatis" />
<!-- 开启springIOC注解方式 -->
<context:annotation-config />
<!-- 导入spring-mybatis.xml配置文件 -->
<import resource="spring-mybatis.xml" />
</beans>
userMapper.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace用接口的全路径作为命名空间 -->
<mapper namespace="com.spring_mybatis.dao.UserDao">
<resultMap type="User" id="userRoleMap" autoMapping="true">
<id column="id" property="id" />
<collection property="roles" ofType="Role"
autoMapping="true">
<id column="role_id" property="role_id" />
</collection>
</resultMap>
<!-- 添加用户信息 -->
<insert id="add" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into t_user(username,password,phone,nickname,email)
values(#{username},#{password},#{phone},#{nickname},#{email})
</insert>
<!-- 分配角色 -->
<insert id="assignRole" parameterType="map">
insert into t_user_role(userid,roleid)
values(#{userid},#{roleid})
</insert>
<!-- 删除用户信息 -->
<delete id="del" parameterType="java.lang.Integer">
delete from t_user where id = #{id}
</delete>
<!-- 删除分配的角色 -->
<delete id="delRole" parameterType="java.lang.Integer">
delete from t_user_role where
userid = #{id}
</delete>
<!-- 修改用户信息 -->
<update id="update" parameterType="User">
update t_user
<set>
<if test="username != null and username != ''">
username = #{username},
</if>
<if test="password != null and password != ''">
password = #{password},
</if>
<if test="phone != null and phone != ''">
phone = #{phone},
</if>
<if test="nickname != null and nickname != ''">
nickname = #{nickname},
</if>
<if test="email != null and email != ''">
email = #{email}
</if>
</set>
where id = #{id}
</update>
<!-- 查询用户信息总条数 -->
<select id="count" resultType="java.lang.Integer">
select count(*) from t_user
</select>
<!-- 根据id查询用户信息 -->
<select id="load" parameterType="java.lang.Integer" resultMap="userRoleMap">
select * from t_user u
left join t_user_role ur on u.id =
ur.userid
left join t_role r on ur.roleid = r.role_id
where u.id = #{id}
</select>
<!-- 查询全部用户信息 -->
<select id="list" resultMap="userRoleMap">
select * from t_user u
left join t_user_role ur on u.id = ur.userid
left join t_role r on ur.roleid =
r.role_id
</select>
</mapper>
BaseDao层
package com.spring_mybatis.dao.common;
import java.util.List;
public interface BaseDao<E> {
// 添加信息
Integer add(E entity);
// 删除信息
Integer del(Integer id);
// 修改信息
Integer update(E entity);
// 根据id查询信息
E load(Integer id);
// 查询全部信息
List<E> list();
}
UserDao层
package com.spring_mybatis.dao;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.spring_mybatis.dao.common.BaseDao;
import com.spring_mybatis.entity.User;
@Repository
public interface UserDao extends BaseDao<User> {
// 删除分配的角色
int delRole(int id);
// 分配角色
int assignRole(Map<String, Object> map);
}
UserService层
package com.spring_mybatis.service;
import java.util.List;
import java.util.Map;
import com.spring_mybatis.entity.User;
public interface UserService {
// 添加用户信息
Integer add(User user);
// 删除用户信息
Integer del(Integer id);
// 修改用户信息
Integer update(User user);
// 根据id查询用户信息
User load(Integer id);
// 查询全部用户信息
List<User> list();
// 删除分配的角色
Integer delRole(Integer id);
// 分配角色
Integer assignRole(Map<String, Object> map);
}
UserServiceImpl层
package com.spring_mybatis.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spring_mybatis.dao.UserDao;
import com.spring_mybatis.entity.User;
import com.spring_mybatis.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public Integer add(User user) {
int i = userDao.add(user);
return i;
}
@Override
public Integer del(Integer id) {
int i = userDao.del(id);
return i;
}
@Override
public Integer update(User user) {
int i = userDao.update(user);
return i;
}
@Override
public User load(Integer id) {
User user = userDao.load(id);
return user;
}
@Override
public List<User> list() {
List<User> users = userDao.list();
return users;
}
@Override
public Integer delRole(Integer id) {
int i = userDao.delRole(id);
return i;
}
@Override
public Integer assignRole(Map<String, Object> map) {
int i = userDao.assignRole(map);
return i;
}
}
UserTest类
package com.spring_mybatis.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring_mybatis.entity.User;
import com.spring_mybatis.service.UserService;
public class UserTest {
// 创建spring工厂
private BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-beans.xml");
// 得到spring工厂所映射的bean
UserService userService = beanFactory.getBean("userService", UserService.class);
// 添加用户信息
@Test
public void addTest() {
User user = new User();
user.setUsername("张三");
user.setPassword("123");
user.setPhone("15365874951");
user.setNickname("小张");
user.setEmail("zhangsan@qq.com");
int i = userService.add(user);
int id = user.getId();
List<String> str = new ArrayList<String>();
str.add("1");
str.add("2");
str.add("3");
Map<String, Object> map = new HashMap<String, Object>();
map.put("userid", id);
int j = 0;
for(String st : str) {
map.put("roleid", st);
j = userService.assignRole(map);
}
if (i == 1 && j == 1) {
System.out.println("添加用户成功!");
} else {
System.out.println("添加用户成功!");
}
}
// 删除用户信息和分配的角色
@Test
public void delTest() {
int id = 2;
int i = userService.del(id);
int j = userService.delRole(id);
if (i == 1 && j == 1) {
System.out.println("删除用户成功!");
} else {
System.out.println("删除用户成功!");
}
}
// 修改用户信息
@Test
public void updateTest() {
User user = new User();
int id = 20;
user.setId(id);
user.setUsername("李四");
user.setPassword("456");
user.setPhone("15365874951");
user.setNickname("小李");
user.setEmail("lisi@qq.com");
int i = userService.update(user);
int j = userService.delRole(id);
List<String> str = new ArrayList<String>();
str.add("1");
str.add("2");
str.add("3");
str.add("4");
Map<String, Object> map = new HashMap<String, Object>();
map.put("userid", id);
int k = 0;
for(String st : str) {
map.put("roleid", st);
k = userService.assignRole(map);
}
if (i == 1 && j == 1 && k == 1) {
System.out.println("修改用户成功!");
} else {
System.out.println("修改用户成功!");
}
}
// 根据id查询用户信息
@Test
public void loadTest() {
int id = 3;
System.out.println(userService.load(id));
}
// 查询全部用户信息
@Test
public void listTest() {
for (User user : userService.list()) {
System.out.println(user);
}
}
}