使用篇SpringBoot整合mybatis

Posted myitnews

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用篇SpringBoot整合mybatis相关的知识,希望对你有一定的参考价值。

说明:使用SpringBoot+Mybatis+Jsp实现简单的用户增删查改

#用户表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

1. 创建项目Maven Project,修改pom.xml

<properties>
        <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    <!-- jasper:jsp引擎 -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.5</version>
    </dependency>
    <!-- mysql 数据库驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- druid 数据库连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.12</version>
    </dependency>
</dependencies>

2. 在src/main/resources目录下新建application.properties并添加全局配置

#数据库基本信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#这里要注意&,可能在spring的xml中我们用的是转义符号(&amp;),但是在这里不用
spring.datasource.url=jdbc:mysql://192.168.178.5:12345/ssm?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

#数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

#myabtis
#扫描mapper的xml映射文件
mybatis.mapper-locations=classpath:mapper/*.xml
#别名
mybatis.type-aliases-package=com.linhw.demo.pojo

#jsp视图映射配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

3. 根据用户表创建实体类

public class User {
    private Integer userId;
    private String userName;
    private Integer age;
    
    public User() {
    }
    public User(Integer userId, String userName, Integer age) {
        this.userId = userId;
        this.userName = userName;
        this.age = age;
    }
    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer 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;
    }
}

4. 创建 mapper 接口以及映射配置文件

public interface UserMapper {

    void insertUser(User user);
    List<User> selectAllUser();
    User selectUserById(Integer userId);
    void editUser(User user);
    void removeUser(Integer userId);
    
}

在src/main/resources目录下新建mapper文件夹,在mapper下创建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.linhw.demo.dao.UserMapper">
    <!-- 插入 -->
    <insert id="insertUser" parameterType="user">
        insert into
        user(user_name,age) values(#{userName},#{age})
    </insert>

    <!-- 查询所有用户 -->
    <select id="selectAllUser" resultMap="BaseResultMap"> 
        select user_id,user_name,age from user
    </select>
    
    <!-- 查询用户信息 -->
    <select id="selectUserById" resultMap="BaseResultMap" parameterType="Integer">
        select user_id,user_name,age from user where user_id = #{userId}
    </select>
    
    <!-- 修改用户信息 -->
    <update id="editUser" parameterType="user">
        update user set user_name=#{userName},age=#{age} where user_id=#{userId}
    </update>
    
    <!-- 删除用户 -->
    <delete id="removeUser" parameterType="Integer">
        delete from user where user_id=#{userId}
    </delete>
    
    <resultMap id="BaseResultMap" type="user">
        <id column="user_id" jdbcType="BIGINT" property="userId" />
        <result column="user_name" jdbcType="VARCHAR" property="userName" />
        <result column="age" jdbcType="BIGINT" property="age" />
    </resultMap> 
    
</mapper>

5. 编写业务层代码

//接口
public interface UserService {

    void addUser(User user);
    
    List<User> findAllUser();
    
    User findUserById(Integer userId);
    
    void updateUser(User user);
    
    void delUserById(Integer userId);
}
//实现类
@Service
@Transactional
public class UserServiceImpl implements UserService{
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public void addUser(User user) {
        userMapper.insertUser(user);
    }

    @Override
    public List<User> findAllUser() {
        return userMapper.selectAllUser();
    }

    @Override
    public User findUserById(Integer userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public void updateUser(User user) {
        userMapper.editUser(user);
    }

    @Override
    public void delUserById(Integer userId) {
        userMapper.removeUser(userId);
    }
}

6. 创建Controller

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;

    /*** 页面跳转 */
    @RequestMapping("/{page}")
    public Object showPage(@PathVariable String page) {
        ModelAndView view = new ModelAndView();
        view.setViewName(page);
        return view;
    }
    /*** 添加用户 */
    @RequestMapping("/addUser")
    public Object addUser(Model model, User user) {
        userService.addUser(user);
        ModelAndView view = new ModelAndView();
        model.addAttribute("status", "成功");
        view.addObject(model);
        view.setViewName("ok");
        return view;
    }
    /*** 查询所有用户*/
    @RequestMapping("/findAllUser")
    public Object findAllUser(Model model){
        List<User> userList = userService.findAllUser();
        model.addAttribute("list", userList);
        
        ModelAndView view = new ModelAndView();
        view.addObject(model);
        view.setViewName("showUsers");
        return view;
    }
    
    /*** 查询用户信息 */
    @RequestMapping("/findUserById/{id}")
    public Object findUserById(Model model, @PathVariable Integer id){
        User user = userService.findUserById(id);
        model.addAttribute("user", user);
        
        ModelAndView view = new ModelAndView();
        view.addObject(model);
        view.setViewName("updateUser");
        return view;
    }
    
    /*** 修改用户 */
    @RequestMapping("/editUser")
    public Object updateUser(Model model, User user){
        userService.updateUser(user);
        ModelAndView view = new ModelAndView();
        model.addAttribute("status", "成功");
        view.addObject(model);
        view.setViewName("ok");
        return view;
    }
    
    /*** 删除用户 */
    @RequestMapping("/delUserById/{id}")
    public Object delUserById(Model model, @PathVariable Integer id){
        userService.delUserById(id);
        ModelAndView view = new ModelAndView();
        model.addAttribute("status", "成功");
        view.addObject(model);
        view.setViewName("ok");
        return view;
    }
}

7. 编写启动类

@SpringBootApplication
@MapperScan("com.linhw.demo.dao") //用于扫描Mapper接口,生成代理对象,也可以在每一个接口加上@Mapper注解
public class App {
    
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}

8. 视图jsp

(1) 添加用户:input.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>添加用户</title>
</head>
<body>
    <h3>添加用户:</h3>
    <form action="/user/addUser" method="post">
        用户姓名:<input type="text" name="userName" /><br/> 
        用户年龄:<input type="text" name="age" /><br/> 
        <input type="submit" value="确定" /><br />
    </form>
</body>
</html>

技术图片

(2) 用户列表:showUsers.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用户列表</title>
</head>
<body>
<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach items="${list}" var="user">
            <tr>
                <td>${user.userId }</td>
                <td>${user.userName }</td>
                <td>${user.age }</td>
                <td>
                    <a href="/user/findUserById/${user.userId}">更改</a>
                    <a href="/user/delUserById/${user.userId}">删除</a>
                </td>
            </tr>
        </c:forEach>
    </tbody>
</table>
</body>
</html>

技术图片

(3) 修改用户:updateUser.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>修改用户</title>
</head>
<body>
    <h3>修改用户:</h3>
    <form action="/user/editUser" method="post">
        <input type="hidden" name="userId" value="${user.userId }"/>
        用户姓名:<input type="text" name="userName" value="${user.userName }"/><br/> 
        用户年龄:<input type="text" name="age" value="${user.age }"/><br/> 
        <input type="submit" value="确定" /><br />
    </form>
</body>
</html>

技术图片

(4) 操作提示页面:ok.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>操作成功</title>
</head>
<body>
    <h5>操作 ${status}</h5>
    <a href="/user/findAllUser">用户列表</a> | 
    <a href="/user/input">添加用户</a>
</body>
</html>

技术图片

9. 总结

开发过程中需要注意:

(1) application.properties必须添加

#指定mapper的xml映射文件,若放到src/main/java对应的包路径下,会因没有编译到类路径下,导致使用的时候找不到对应的sql
mybatis.mapper-locations=classpath:mapper/*.xml

(2) SpringBoot的启动类上必须添加注解@MapperScan,确保能够找到接口,从而生成代理类

(3) 控制层Controller类使用了@RestController注解,会将返回值直接以Json字符串的形式输出,如果想要返回页面,需使用ModelAndView。

以上是关于使用篇SpringBoot整合mybatis的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot使用Mybatis-PageHelper

SpringBoot整合Mybatis之进门篇

SpringBoot整合Mybatis之JavaWeb应用配置篇

SpringBoot整合Mybatis

springboot整合mybatis以及mybatisplus

springboot整合mybatis以及mybatisplus