SpringBoot代码实战(MyBatis-Plus+Thymeleaf)

构建项目

修改pom.xml文件,添加其他依赖以及设置

java 复制代码
        <!--MyBatis-Plus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
            <version>3.5.6</version>
        </dependency>
        <!-- Druid依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>

配置文件

java 复制代码
spring.application.name=crm

spring.thymeleaf.cache=false

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456

logging.level.root=warn
logging.level.com.ktjiaoyu.mybatisplus.mapper=trace
logging.pattern.console=%p%m%n
#加载sql日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始化大小、最小、最大连接数
spring.datasource.druid.initial-size=3, 
spring.datasource.druid.min-idle=3
spring.datasource.druid.max-active=10
#配置获取连接等待超时的时间
spring.datasource.druid.max-wait=60000
#监控后台账号和密码
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin
#配置StatFilter
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000

模型开发

模型包括entity、mapper、service

entity

实体类User、Role,使用注解配置映射,且配置好关联关系

User

java 复制代码
package com.tykj.crm.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Data;

/**
 * 
 * @TableName sys_user
 */
@TableName(value ="sys_user")
@Data
public class User implements Serializable {
    /**
     * 编号
     */
    @TableId(type = IdType.AUTO)
    private Long usrId;

    /**
     * 姓名
     */
    private String usrName;

    /**
     * 密码
     */
    private String usrPassword;

    /**
     * 角色编号
     */
    private Long usrRoleId;
    private String roleName;

    /**
     * 状态
     */
    private Integer usrFlag;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        User other = (User) that;
        return (this.getUsrId() == null ? other.getUsrId() == null : this.getUsrId().equals(other.getUsrId()))
            && (this.getUsrName() == null ? other.getUsrName() == null : this.getUsrName().equals(other.getUsrName()))
            && (this.getUsrPassword() == null ? other.getUsrPassword() == null : this.getUsrPassword().equals(other.getUsrPassword()))
            && (this.getUsrRoleId() == null ? other.getUsrRoleId() == null : this.getUsrRoleId().equals(other.getUsrRoleId()))
            && (this.getUsrFlag() == null ? other.getUsrFlag() == null : this.getUsrFlag().equals(other.getUsrFlag()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getUsrId() == null) ? 0 : getUsrId().hashCode());
        result = prime * result + ((getUsrName() == null) ? 0 : getUsrName().hashCode());
        result = prime * result + ((getUsrPassword() == null) ? 0 : getUsrPassword().hashCode());
        result = prime * result + ((getUsrRoleId() == null) ? 0 : getUsrRoleId().hashCode());
        result = prime * result + ((getUsrFlag() == null) ? 0 : getUsrFlag().hashCode());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", usrId=").append(usrId);
        sb.append(", usrName=").append(usrName);
        sb.append(", usrPassword=").append(usrPassword);
        sb.append(", usrRoleId=").append(usrRoleId);
        sb.append(", usrFlag=").append(usrFlag);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

Role

java 复制代码
package com.tykj.crm.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Data;

/**
 * 
 * @TableName sys_role
 */
@TableName(value ="sys_role")
@Data
public class Role implements Serializable {
    /**
     * 编号
     */
    @TableId(type = IdType.AUTO)
    private Long roleId;

    /**
     * 角色名称
     */
    private String roleName;

    /**
     * 角色描述
     */
    private String roleDesc;

    /**
     * 状态
     */
    private Integer roleFlag;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        Role other = (Role) that;
        return (this.getRoleId() == null ? other.getRoleId() == null : this.getRoleId().equals(other.getRoleId()))
            && (this.getRoleName() == null ? other.getRoleName() == null : this.getRoleName().equals(other.getRoleName()))
            && (this.getRoleDesc() == null ? other.getRoleDesc() == null : this.getRoleDesc().equals(other.getRoleDesc()))
            && (this.getRoleFlag() == null ? other.getRoleFlag() == null : this.getRoleFlag().equals(other.getRoleFlag()));
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getRoleId() == null) ? 0 : getRoleId().hashCode());
        result = prime * result + ((getRoleName() == null) ? 0 : getRoleName().hashCode());
        result = prime * result + ((getRoleDesc() == null) ? 0 : getRoleDesc().hashCode());
        result = prime * result + ((getRoleFlag() == null) ? 0 : getRoleFlag().hashCode());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", roleId=").append(roleId);
        sb.append(", roleName=").append(roleName);
        sb.append(", roleDesc=").append(roleDesc);
        sb.append(", roleFlag=").append(roleFlag);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

mapper

UserMapper

java 复制代码
package com.ktjiaoyu.thymeleaf.mapper;

import com.ktjiaoyu.thymeleaf.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.PathVariable;


import java.util.List;

/**
* @author Administrator
* @description 针对表【sys_user】的数据库操作Mapper
* @createDate 2024-09-09 09:10:40
* @Entity com.ktjiaoyu.thymeleaf.entity.User
*/
public interface UserMapper extends BaseMapper<User> {

    User login(@Param("usrName") String usrName, @Param("usrPassword") String usrPassword);
    List<User> findAllUsers(@Param("usrName") String usrName, @Param("roleId") Integer roleId, @Param("pageIndex")Integer pageIndex, @Param("pageSize")Integer pageSize);

    public Integer count(@Param("usrName") String usrName, @Param("roleId") Integer roleId);

    User getUserById(Integer usrId);
}

RoleMapper

java 复制代码
package com.ktjiaoyu.thymeleaf.mapper;

import com.ktjiaoyu.thymeleaf.entity.Role;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
* @author Administrator
* @description 针对表【sys_role】的数据库操作Mapper
* @createDate 2024-09-20 14:17:54
* @Entity com.ktjiaoyu.thymeleaf.entity.Role
*/
public interface RoleMapper extends BaseMapper<Role> {

}

sql映射文件

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">
<mapper namespace="com.ktjiaoyu.thymeleaf.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.ktjiaoyu.thymeleaf.entity.User">
        <id property="usrId" column="usr_id" jdbcType="BIGINT"/>
        <result property="usrName" column="usr_name" jdbcType="VARCHAR"/>
        <result property="usrPassword" column="usr_password" jdbcType="VARCHAR"/>
        <result property="usrRoleId" column="usr_role_id" jdbcType="BIGINT"/>
        <result property="usrFlag" column="usr_flag" jdbcType="INTEGER"/>
        <result property="roleName" column="role_name"/>
    </resultMap>

    <sql id="Base_Column_List">
        usr_id,usr_name,usr_password,
        usr_role_id,usr_flag
    </sql>
    <select id="findAllUsers" resultMap="BaseResultMap">
        select u.*,r.role_name
        from sys_user u
            left join sys_role r on u.usr_role_id=r.role_id
        <where>
            <if test="usrName != null and usrName != ''">
                and u.usr_name like '%${usrName}%'
            </if>
            <if test="roleId != null and roleId != 0">
                and u.usr_role_id = #{roleId}
            </if>
        </where>
        limit #{pageIndex},#{pageSize}
    </select>
    <select id="login" resultMap="BaseResultMap">
        select u.*,r.role_name
        from sys_user u
                 left join sys_role r on u.usr_role_id=r.role_id
        where
             u.usr_name = #{usrName}
        and
            u.usr_password = #{usrPassword}
    </select>
    <select id="count" resultType="java.lang.Integer">
        select count(*) from sys_user
        <where>
            <if test="usrName != null and usrName != ''">
                and usr_name like '%${usrName}%'
            </if>
            <if test="roleId != null and roleId != 0">
                and usr_role_id = #{roleId}
            </if>
        </where>
    </select>
    <select id="getUserById" resultType="com.ktjiaoyu.thymeleaf.entity.User">
        select u.*,r.role_name
        from sys_user u
                 left join sys_role r on u.usr_role_id=r.role_id
        where
            u.usr_id = #{usrId}
    </select>
</mapper>

RoleMapper

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">
<mapper namespace="com.ktjiaoyu.thymeleaf.mapper.RoleMapper">

    <resultMap id="BaseResultMap" type="com.ktjiaoyu.thymeleaf.entity.Role">
            <id property="roleId" column="role_id" jdbcType="BIGINT"/>
            <result property="roleName" column="role_name" jdbcType="VARCHAR"/>
            <result property="roleDesc" column="role_desc" jdbcType="VARCHAR"/>
            <result property="roleFlag" column="role_flag" jdbcType="INTEGER"/>
    </resultMap>

    <sql id="Base_Column_List">
        role_id,role_name,role_desc,
        role_flag
    </sql>
</mapper>

service

UserService、UserServiceImpl

java 复制代码
package com.ktjiaoyu.thymeleaf.service;

import com.ktjiaoyu.thymeleaf.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;


import java.util.List;

/**
* @author Administrator
* @description 针对表【sys_user】的数据库操作Service
* @createDate 2024-09-09 09:10:40
*/
public interface UserService extends IService<User> {

    public User login(String usrName, String usrPassword);

    public User addUser(User user);

    public void deleteUser(Integer usrId);

    public User updateUser(User user);

    public User getUser(Long usrId);

    public List<User> selectPageUsers(String usrName, Integer roleId, Integer pageIndex, Integer pageSize);

    public int countInt(String usrName, Integer roleId);

    User getUserById(Integer usrId);
}
java 复制代码
package com.ktjiaoyu.thymeleaf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.thymeleaf.entity.User;

import com.ktjiaoyu.thymeleaf.service.UserService;
import com.ktjiaoyu.thymeleaf.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author Administrator
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2024-09-09 09:10:40
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    @Override
    public User login(String usrName, String usrPassword) {
        return userMapper.login(usrName, usrPassword);
    }

    @Override
    public User addUser(User user) {
        int result = userMapper.insert(user);
        if (result > 0){
            return user;
        }else{
            return null;
        }
    }

    @Override
    public void deleteUser(Integer usrId) {
        userMapper.deleteById(usrId);
    }

    @Override
    public User updateUser(User user) {
        int i = userMapper.updateById(user);
        return user;
    }

    @Override
    public User getUser(Long usrId) {
        return userMapper.selectById(usrId);
    }

    @Override
    public List<User> selectPageUsers(String usrName, Integer roleId, Integer pageIndex, Integer pageSize) {
        return userMapper.findAllUsers(usrName, roleId, pageIndex, pageSize);
    }

    @Override
    public int countInt(String usrName, Integer roleId) {
        return userMapper.count(usrName, roleId);
    }

    @Override
    public User getUserById(Integer usrId) {
        return userMapper.getUserById(usrId);
    }
}

RoleService、RoleServiceImpl

java 复制代码
package com.ktjiaoyu.thymeleaf.service;

import com.ktjiaoyu.thymeleaf.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;

/**
* @author Administrator
* @description 针对表【sys_role】的数据库操作Service
* @createDate 2024-09-20 14:17:54
*/
public interface RoleService extends IService<Role> {

}
java 复制代码
package com.ktjiaoyu.thymeleaf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.thymeleaf.entity.Role;
import com.ktjiaoyu.thymeleaf.service.RoleService;
import com.ktjiaoyu.thymeleaf.mapper.RoleMapper;
import org.springframework.stereotype.Service;

/**
* @author Administrator
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2024-09-20 14:17:54
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{

}

控制器开发

列表(联表加分页)

java 复制代码
    @RequestMapping("/user/list")
    public String findUsers(Model model, String usrName, Integer roleId, @RequestParam(defaultValue = "1") Integer pageIndex){
        System.out.println(usrName + "/" + roleId);
        // 分页对象
        Page<User> userPage = new Page<>();
        // 当前页数
        userPage.setPageNo(pageIndex);
        // 页面数据量
        userPage.setPageSize(5);
        // 获取页面数据总量
        userPage.setTotalCount(userService.countInt(usrName, roleId));
        // 获取分页数据列表
        userPage.setData(userService.selectPageUsers(usrName,roleId,( userPage.getPageNo() - 1 ) * userPage.getPageSize(),userPage.getPageSize()));
        // 获取角色数据列表
        List<Role> roles = roleService.list();
        // 传递分页数据
        model.addAttribute("userPager",userPage);
        // 传递角色数据列表
        model.addAttribute("roles",roles);
        // 数据回显
        model.addAttribute("usrName",usrName);
        model.addAttribute("roleId",roleId);
        return "user/list";
    }

新增、修改

java 复制代码
    @RequestMapping("/user/save")
    public String save(User user){
        if (user.getUsrId() != null){
            userService.updateUser(user);
        }else{
            userService.save(user);
        }
        return "redirect:/user/list";
    }

删除

java 复制代码
    @ResponseBody
    @RequestMapping("/user/del/{usrId}")
    public String del(@PathVariable Integer usrId){
        userService.deleteUser(usrId);
        Map map = new HashMap();
        map.put("result","true");
        return JSONUtils.toJSONString(map);
    }
相关推荐
qq_4419960515 分钟前
Mybatis官方生成器使用示例
java·mybatis
巨大八爪鱼22 分钟前
XP系统下用mod_jk 1.2.40整合apache2.2.16和tomcat 6.0.29,让apache可以同时访问php和jsp页面
java·tomcat·apache·mod_jk
码上一元2 小时前
SpringBoot自动装配原理解析
java·spring boot·后端
计算机-秋大田2 小时前
基于微信小程序的养老院管理系统的设计与实现,LW+源码+讲解
java·spring boot·微信小程序·小程序·vue
魔道不误砍柴功4 小时前
简单叙述 Spring Boot 启动过程
java·数据库·spring boot
失落的香蕉4 小时前
C语言串讲-2之指针和结构体
java·c语言·开发语言
枫叶_v4 小时前
【SpringBoot】22 Txt、Csv文件的读取和写入
java·spring boot·后端
wclass-zhengge4 小时前
SpringCloud篇(配置中心 - Nacos)
java·spring·spring cloud
路在脚下@4 小时前
Springboot 的Servlet Web 应用、响应式 Web 应用(Reactive)以及非 Web 应用(None)的特点和适用场景
java·spring boot·servlet
黑马师兄4 小时前
SpringBoot
java·spring