完整源码下载:https://pan.baidu.com/s/1rNQKSnqGEO2eQJYdd0UJwA 提取码: 59s5

前篇 SpringBoot+JdbcTemplate实现数据库多联表增删改查及分页实例

这次用Mybatis重构,之后工作中大概用的比较多

相比Jpa和JdbcTemplate复杂一些,多了几个配置文件,数据库查询方式也是更像HTML风格,实体类服务层dao接口倒是简化了很多,只用写一个了

开发环境:

IDE:IDEA

开发框架:SpringBoot、Maven

JDK版本:1.8

数据库:MySql 5.7.28

调试软件:Postman安装与使用

数据库结构

  1. 用户表结构:id 名字 密码 邮箱
  2. 角色表结构:id 角色名
  3. 用户-角色表结构:id 用户id 角色id

功能总结:

  1. 增加用户
  2. 更新用户
  3. 根据id删除用户
  4. 根据id查找用户
  5. 根据用户名查找用户 (模糊查询)
  6. 分页展示所有用户
  7. 根据用户id增加角色
  8. 根据用户id删除指定角色
  9. 根据用户id查询所有角色
  10. 根据用户名查询所有角色
  11. 根据角色id查询所有用户
  12. 根据角色名查询所有用户

项目结构: 

新建项目:

打开IDEA->File->New->Project,选择Spring Initializr

然后修改Group名称,Type选择Maven,Java version选择8   (JDK8和JDK1.8是一样的)

依次选择如右侧的配置 

修改工程文件名,新建项目完成

代码文件

首先是Mybats的配置文件,分别创建这三个包和类

主要是用来配置数据库(也可以不写,不过我删了之后就跑不起来了。。

可以直接复制,包名改成自己的就行了

DataSourceConfiguration类

package com.example.mybatis.demo.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.beans.PropertyVetoException;

/**
 * 数据库配置类
 */
@Configuration
public class DataSourceConfiguration {

    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    @Bean(name = "dataSouce")
    public ComboPooledDataSource createDataSouce() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(jdbcUsername);
        dataSource.setPassword(jdbcPassword);
        //关闭连接后不自动commit
        dataSource.setAutoCommitOnClose(false);
        return dataSource;
    }
}

SessionFactoryConfiguration类

package com.example.mybatis.demo.config.dao;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * 数据库sqlSession配置类
 */

@Configuration
public class SessionFactoryConfiguration {

    @Value("${mapper_path}")
    private String mapperPath;

    @Value("${mybatis_config_file}")
    private String mybatisConfigFilePath;

    @Autowired
    private DataSource dataSouce;
    @Value("${entity_package}")
    private String entityPackage;

    @Bean(name="sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFilePath));
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = PathMatchingResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX+mapperPath;
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(packageSearchPath));
        sqlSessionFactoryBean.setDataSource(dataSouce);
        sqlSessionFactoryBean.setTypeAliasesPackage(entityPackage);
        return sqlSessionFactoryBean;
    }
}

 TransactionManagementConfiguration类

package com.example.mybatis.demo.config.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

/**
 * 事务配置类,不可缺少,尚未知具体作用
 */
@Configuration
@EnableTransactionManagement
public class TransactionManagementConfiguration implements TransactionManagementConfigurer{

    @Autowired
    private DataSource dataSource;

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}

pom.xml配置文件

多了一个线程池配置

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example.mybaties</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--线程池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.4</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

application.properties配置文件

更喜欢yml文件的格式,不过不知道mybatis的部分怎么改...

注意数据库的配置,改成自己的

#1.项目启动的端口
server.port=8080
#2.数据库连接参数
#2.1jdbc驱动,示数据库厂商决定,这是mysql的驱动
jdbc.driver=com.mysql.cj.jdbc.Driver
#2.2数据库连接url,包括ip(127.0.0.1)、端口(3306)、数据库名(testdb)
jdbc.url=jdbc:mysql://127.0.0.1:3306/你的数据库?useUnicode=true&characterEncoding=utf-8&useSSL=false
#2.3数据库账号名
jdbc.username=你的账号名
#2.4数据库密码
jdbc.password=你的密码
#3.Mybatis配置
#3.1 mybatis配置文件所在路径
mybatis_config_file=mybatis-config.xml
#3.2 mapper文件所在路径,这样写可匹配mapper目录下的所有mapper,包括其子目录下的
mapper_path=/mapper/*.xml
#3.3 entity所在包
entity_package=com.example.mybatis.demo.entity

实体类

新建文件夹entity,创建实体类User

package com.example.mybatis.demo.entity;

public class User {

    protected Integer id;

    protected String name;

    protected String password;

    protected String email;

    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 String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

创建实体类Role 

package com.example.mybatis.demo.entity;

public class Role {

    private Integer id;

    private String role;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}

创建实体类User_Role

package com.example.mybatis.demo.entity;

public class User_Role {

    private Integer id;

    private Integer user_id;

    private Integer role_id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getUser_id() {
        return user_id;
    }

    public void setUser_id(Integer user_id) {
        this.user_id = user_id;
    }

    public Integer getRole_id() {
        return role_id;
    }

    public void setRole_id(Integer role_id) {
        this.role_id = role_id;
    }
}

 

Dao接口

新建文件夹dao,创建接口类文件userDao

接口类文件创建方法:对应文件夹右键,New->Java Class,然后选择Interface创建

package com.example.mybatis.demo.dao;

import com.example.mybatis.demo.entity.Role;
import com.example.mybatis.demo.entity.User;
import com.example.mybatis.demo.entity.User_Role;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface Dao {

    int addUser(User user);

    User findById(Integer id);

    int addRoleById(User_Role user_role);

    int delRoleById(User_Role user_role);

    int update(User user);

    List<User> findByName(String name);

    int delete(Integer id);

    List<Role> findRoleByUserName(String name);

    List<User> findUserByRoleName(String name);

    List<Role> findRoleByUserId(Integer id);

    List<User> findUserByRoleId(Integer id);

    List<User> findAll(Integer page);

}

 

服务层接口类

新建文件夹service,创建a接口类文件UserService

package com.example.mybatis.demo.service;

import com.example.mybatis.demo.dao.Dao;
import com.example.mybatis.demo.entity.Role;
import com.example.mybatis.demo.entity.User;
import com.example.mybatis.demo.entity.User_Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private Dao Dao;

    public int addUser(User user) {
        return Dao.addUser(user);
    }

    public User findById(Integer id) {
        return Dao.findById(id);
    }

    //根据名字查找
    public List<User> findByName(String name) {
        return Dao.findByName(name);
    }

    //根据用户名查找用户所有的角色
    public List<Role> findRoleByUserName(String name) {
        return Dao.findRoleByUserName(name);
    }

    //根据角色名查找所有的用户
    public List<User> findUserByRoleName(String name) {
        return Dao.findUserByRoleName(name);
    }

    //根据id删除
    public int deleteById(Integer id) {
        return Dao.delete(id);
    }

    public int addRoleById(User_Role user_role) {
        return Dao.addRoleById(user_role);
    }

    public int delRoleById(User_Role user_role) {
        return Dao.delRoleById(user_role);
    }

    public int updateUser(User user) {
        return Dao.update(user);
    }

    public List<Role> findRoleByUserId(Integer id) {
        return Dao.findRoleByUserId(id);
    }

    public List<User> findUserByRoleId(Integer id) {
        return Dao.findUserByRoleId(id);
    }

    //查询所有
    public List<User> findAll(Integer page) {
        return Dao.findAll(page);
    }
}

控制层

新建文件夹controller,创建控制类文件UserController

功能注释都在这里了

package com.example.mybatis.demo.controller;

import com.example.mybatis.demo.entity.Role;
import com.example.mybatis.demo.entity.User;
import com.example.mybatis.demo.entity.User_Role;
import com.example.mybatis.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/emp")
public class Controller {

    @Autowired
    private UserService userService;

    /**
     * 增加用户
     *
     * @param user
     * @return
     */
    @PutMapping("/add")
    public String add(User user) {
        userService.addUser(user);
        return "增加用户成功";
    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delById/{id}")
    public String delById(@PathVariable Integer id) {
        userService.deleteById(id);
        return "删除用户成功";
    }

    /**
     * 通过id查找用户
     *
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public User findById(@PathVariable Integer id) {
        System.out.println("id:" + id);
        return userService.findById(id);
    }

    /**
     * 通过用户名模糊查询
     *
     * @param name
     * @return
     */
    @GetMapping("/findByName/{name}")
    public List<User> findByName(@PathVariable String name) {
        return userService.findByName(name);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @PostMapping("/update")
    public String update(User user) {
        userService.updateUser(user);
        return "更新用户成功";
    }

    /**
     * 通过用户名查找所有角色
     *
     * @param name
     * @return
     */
    @GetMapping("/findRoleByUserName/{name}")
    public List<Role> findRoleByUserName(@PathVariable String name) {
        return userService.findRoleByUserName(name);
    }

    /**
     * 通过角色名查找所有用户
     *
     * @param name
     * @return
     */
    @GetMapping("/findUserByRoleName/{name}")
    public List<User> findUserByRoleName(@PathVariable String name) {
        return userService.findUserByRoleName(name);
    }

    /**
     * 根据用户id查找角色
     *
     * @param id
     * @return
     */
    @GetMapping("/findRoleByUserId/{id}")
    public List<Role> findRoleByUserId(@PathVariable Integer id) {
        return userService.findRoleByUserId(id);
    }

    /**
     * 根据角色id查找用户
     *
     * @return
     */
    @GetMapping("/findUserByRoleId/{id}")
    public List<User> findUserByRoleId(@PathVariable Integer id) {
        return userService.findUserByRoleId(id);
    }

    /**
     * 分页查看所有用户
     *
     * @param page
     * @return
     */
    @GetMapping("/findAll/{page}")
    public List<User> findAll(@PathVariable Integer page) {
        page = (page - 1) * 5;
        return userService.findAll(page);
    }

    /**
     * 通过用户id和角色id增加角色
     *
     * @param user_role
     * @return
     */
    @PutMapping("/addRoleById")
    public String addRoleById(User_Role user_role) {
        userService.addRoleById(user_role);
        return "增加角色成功";
    }

    /**
     * 通过用户id和角色id删除指定角色
     *
     * @param user_role
     * @return
     */
    @DeleteMapping("/delRoleById")
    public String delRoleById(User_Role user_role) {
        userService.delRoleById(user_role);
        return "删除角色成功";
    }
}

关联层

在resouces文件夹下新建mapper包,创建DaoMapper.xml文件

这里是Mybatis写SQL语句的地方,风格类似HTML标签

传递List数据类型的时候需要写一个RestMap,将主要参数写进去

模糊查询那里(findByName)需要注意一下格式,使用concat将%与参数连接起来

<?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" >
<mapper namespace="com.example.mybatis.demo.dao.Dao">
    <!-- 根据主键查询-->
    <!--SQL操作方法  返回参数格式  传入参数格式参数-->
    <select id="findById" resultType="com.example.mybatis.demo.entity.User" parameterType="java.lang.Integer" >
        select * from user where id = #{id}
    </select>
    <insert id="addUser" parameterType="com.example.mybatis.demo.entity.User" >
        INSERT INTO user(id,name,password,email) VALUE(#{id},#{name},#{password},#{email})
    </insert>
    <delete id="delete" parameterType="java.lang.Integer" >
        DELETE FROM user where id = #{id}
    </delete>
    <update id="update" parameterType="com.example.mybatis.demo.entity.User" >
        UPDATE user
        <set>
            <if test="name!=null and name!='' ">
                name= #{name},
            </if>
            <if test="password!=null">
                password= #{password},
            </if>
            <if test="email!=null">
                email= #{email},
            </if>
        </set>
        WHERE id= #{id};
    </update>
    <resultMap id="result" type="com.example.mybatis.demo.entity.User">
        <result property="id" column="id" />
        <result property="name" column="name" />
        <result property="password" column="password"/>
        <result property="email" column="email"/>
    </resultMap>
    <select id="findByName" resultMap="result" parameterType="java.lang.String">
        SELECT user.id,user.name,user.password,user.email FROM user WHERE name like concat('%',#{name},'%')
    </select>
    <resultMap id="resultRole" type="com.example.mybatis.demo.entity.Role">
        <result property="id" column="id" />
        <result property="role" column="role" />
    </resultMap>
    <select id="findRoleByUserName" resultMap="resultRole" parameterType="java.lang.String">
        SELECT role.id,role.role FROM user_role,role WHERE user_role.user_id = (SELECT id FROM user WHERE user.name = #{name}) AND role.id = user_role.role_id;
    </select>
    <select id="findUserByRoleName" resultMap="result" parameterType="java.lang.String">
        SELECT user.id,user.name,user.password,user.email FROM user_role,user WHERE user_role.role_id = (SELECT id FROM role WHERE role.role = #{name}) AND user.id = user_role.user_id;
    </select>
    <select id="findRoleByUserId" resultMap="resultRole" parameterType="java.lang.Integer">
        SELECT role.id,role.role FROM user_role,role WHERE user_role.user_id = #{id} AND role.id = user_role.role_id;
    </select>
    <select id="findUserByRoleId" resultMap="result" parameterType="java.lang.Integer">
        SELECT user.id,user.name,user.password,user.email FROM user_role,user WHERE user_role.role_id = #{id} AND user.id = user_role.user_id;
    </select>
    <select id="findAll" resultMap="result" parameterType="java.lang.Integer">
        SELECT * FROM user LIMIT #{page},5;
    </select>
    <insert id="addRoleById" parameterType="com.example.mybatis.demo.entity.User_Role">
        INSERT INTO user_role(user_id,role_id) VALUE(#{user_id},#{role_id})
    </insert>
    <delete id="delRoleById" parameterType="java.lang.Integer">
        DELETE FROM user_role where user_id = #{user_id} AND role_id = #{role_id}
    </delete>
</mapper>

整体文件结构在文章开头

数据库结构:

user 用户表

id为主键自增非空,int类型
name非空  varchar(10)类型
password   varchar(16)类型
email         varchar(40) 类型
 

role 角色表

 user_role 用户角色关联表

 

测试:

查询全体

查询id

注意链接格式,在源码controller类中使用了RESTful规范进行查询操作

查询名字

增加用户

使用put方法进行传参,id自增所以不用加上

更新用户

删除用户

分页展示

实习的学习过程主要是做了这些,该去实战了(搬砖)

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐