spring-boot集成mybatis

1、 基本步骤

  (1)mysql建库test,建表tb_user

  (2)引入mybatis依赖。    

  (3)添加Dao层、Mapper层、Model层。

  (4)添加数据库配置application.properties。

  (5)完善TestController类。

                         (1)mysql建库test,建表tb_user

          

-- ----------------------------
-- Table structure for `tb_user`
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(8) NOT NULL,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `usersex` tinyint(2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', '32', '1', '1', null);
INSERT INTO `tb_user` VALUES ('2', '张三', '123', '1', null);

          (2)修改pom.xml,添加mybatis依赖和mysql依赖。

                <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        
        
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>        

修改后的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.sun</groupId>
  <artifactId>spring-boot-test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>
    
    <dependencies>
          <!-- web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        
        
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
View Code

          (3)添加Dao层、Mapper层、Model层。

package com.sun.dao;

import java.util.List;

import com.sun.model.User;

public interface UserMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);    

    User selectOne(String username,String password);
    
    List<User> selectAll();

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}
package com.sun.model;

import java.io.Serializable;

public class User implements Serializable{
    private Integer id;

    private String username;

    private String password;

    private String email;

    private Byte usersex;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email == null ? null : email.trim();
    }

    public Byte getUsersex() {
        return usersex;
    }

    public void setUsersex(Byte usersex) {
        this.usersex = usersex;
    }
}

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.sun.dao.UserMapper">
  <resultMap id="BaseResultMap" type="com.sun.model.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    <result column="usersex" jdbcType="TINYINT" property="usersex" />
  </resultMap>
  <sql id="Base_Column_List">
    id, username, password, email, usersex
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from tb_user
    where id = #{id,jdbcType=INTEGER}
  </select>
  <select id="selectOne" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from tb_user
    where username = #{username} and password =  #{password}
  </select>
  <select id="selectAll" resultType="User">
        SELECT * FROM tb_user
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from tb_user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.sun.model.User">
    insert into tb_user (id, username, password, 
      email, usersex)
    values (#{id,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{email,jdbcType=VARCHAR}, #{usersex,jdbcType=TINYINT})
  </insert>
  <insert id="insertSelective" parameterType="com.sun.model.User">
    insert into tb_user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="password != null">
        password,
      </if>
      <if test="email != null">
        email,
      </if>
      <if test="usersex != null">
        usersex,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        #{email,jdbcType=VARCHAR},
      </if>
      <if test="usersex != null">
        #{usersex,jdbcType=TINYINT},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.sun.model.User">
    update tb_user
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        email = #{email,jdbcType=VARCHAR},
      </if>
      <if test="usersex != null">
        usersex = #{usersex,jdbcType=TINYINT},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.sun.model.User">
    update tb_user
    set username = #{username,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      email = #{email,jdbcType=VARCHAR},
      usersex = #{usersex,jdbcType=TINYINT}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

这样mybatis的数据操作层就完成了。

                 (4)添加application.properties

#数据源
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456

#mybatis
mybatis.mapper-locations=classpath*:com/sun/mapping/*Mapper.xml
mybatis.type-aliases-package=com.sun.model

                                                            (5)下来修改controller。

package com.sun.controller;


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

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sun.dao.UserMapper;
import com.sun.model.User;


@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private UserMapper userMapper;
    
    @RequestMapping("/hello")  
    public String hello(){  
        return "Hello world!";  
    }  
    
    @RequestMapping("/all")
    public String findAll(Map<String,Object> map){
        List<User> userList = userMapper.selectAll();
        map.put("hello","from TestController.helloHtml");
        map.put("userList",userList);
        return "/test";
    }
}

输入http://localhost:8080/test/all就可以访问了。

2、总结

  源码https://github.com/sunfengjiajia/spring-boot-test。包含mybatis-generator。

  (1)mybatis有一个生成工具mybatis-generator,我的代码就是工具生成。很好用。

      我将工具放在根目录下新建的config文件夹下了,所以一定要注意配置文件的路径。

  (2)要在启动类添加扫描    

//mapper 接口类扫描包配置
@MapperScan("com.sun.dao")

  (3)要在application.properties文件添加关联信息

#mybatis
mybatis.mapper-locations=classpath*:com/sun/mapping/*Mapper.xml
mybatis.type-aliases-package=com.sun.model
欢迎大家加我qq:309620263探讨技术问题。
原文地址:https://www.cnblogs.com/PPBoy/p/7126227.html