spring-boot:spring-boot2.0集成mybatis

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mr_OOO/article/details/84930318

如何集成

添加依赖

此处默认已配置好连接池,如果不清楚连接池配置的,请参考:spring boot:spring boot2.0配置druid连接池

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!-- mybatis分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>

建议有分页情况下,使用分页插件,既可以使代码变得简洁,利于维护,也可以提高开发效率。

代码生成器

一般情况下,使用mybatis都不会自己去写modeldao,和mapper,这里推荐我常用的代码生成器:

  1. mybatis-generator-core

所有的mybatis代码生成器都是基于原生mybatis-generator开始修改的,我这里加了中文注释功能,有兴趣的同学可以继续自己修改。

  1. mybatis-generator-gui

带界面的代码生成器,功能还比较齐全,对mybatis-generator-core使用方法还不太了解的同学可以选择这个。

编辑配置文件

#mybatis xml文件位置
mybatis.mapper-locations=classpath:mapper/*.xml
#打印SQL
logging.level.com.ouyanglol.demo.dao=debug

添加MapperScan

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Ouyang
 */
@SpringBootApplication
@MapperScan(basePackages = "com.ouyanglol.demo.dao")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

如果不配置@MapperScanmybaties的没一个Mapper类都需要添加@Mapper注解,很麻烦,建议使用@MapperScan

测试

测试代码

controller

package com.ouyanglol.demo.controller;

import com.github.pagehelper.PageInfo;
import com.ouyanglol.demo.model.User;
import com.ouyanglol.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Ouyang
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("list")
    public String list() {
        PageInfo<User> pageInfo = userService.all();
        log.info("total-->{}",pageInfo.getTotal());
        StringBuilder builder = new StringBuilder();
        pageInfo.getList().forEach(user -> builder.append(user.toString()));
        log.info("userList-->{}",builder.toString());
        log.info("一共{}页",pageInfo.getPages());
        return builder.toString();
    }
}

service

import com.github.pagehelper.PageInfo;
import com.ouyanglol.demo.model.User;

/**
 * @author Ouyang
 */
public interface UserService {

    /**
     * 查询所有用户
     * @return 用户列表
     */
    PageInfo<User> all();

}
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ouyanglol.demo.dao.UserDAO;
import com.ouyanglol.demo.model.User;
import com.ouyanglol.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @author Ouyang
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Override
    public PageInfo<User> all() {
        //开始分页,查询第1页,每页3条数据
        PageHelper.startPage(1,3);
        return new PageInfo<>(userDAO.selectAll());
    }
}

dao

package com.ouyanglol.demo.dao;

import java.io.Serializable;

/**
 * DAO公共基类,由MybatisGenerator自动生成请勿修改
 * @author Ouyang
 * @param <Model> The Model Class 这里是泛型不是Model类
 * @param <PK> The Primary Key Class 如果是无主键,则可以用Model来跳过,如果是多主键则是Key类
 */
public interface MyBatisBaseDao<Model, PK extends Serializable> {
    /**
     * 删除
     * @param id 主键
     * @return int
     */
    int deleteByPrimaryKey(PK id);

    /**
     * 添加
     * @param record 实体
     * @return int
     */
    int insert(Model record);

    /**
     * 增加
     * @param record 实体
     * @return int
     */
    int insertSelective(Model record);

    /**
     * 根据主键查询
     * @param id id
     * @return 实体
     */
    Model selectByPrimaryKey(PK id);

    /**
     * 更新
     * @param record 实体
     * @return int
     */
    int updateByPrimaryKeySelective(Model record);

    /**
     * 更新
     * @param record 实体
     * @return int
     */
    int updateByPrimaryKey(Model record);
}
package com.ouyanglol.demo.dao;

import com.ouyanglol.demo.model.User;

import java.util.List;

/**
 * UserDAO继承基类
 * @author Ouyang
 */
public interface UserDAO extends MyBatisBaseDao<User, String> {
    /**
     * 查询所有用户
     * @return 用户列表
     */
    List<User> selectAll();
}

mapper

<?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.ouyanglol.demo.dao.UserDAO">
    <resultMap id="BaseResultMap" type="com.ouyanglol.demo.model.User">
        <id column="id" jdbcType="VARCHAR" property="id"/>
        <result column="userName" jdbcType="VARCHAR" property="username"/>
        <result column="sex" jdbcType="VARCHAR" property="sex"/>
        <result column="age" jdbcType="INTEGER" property="age"/>
    </resultMap>
    <sql id="Base_Column_List">
      id, userName, sex, age
    </sql>
    <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from user
        where id = #{id,jdbcType=VARCHAR}
    </select>
    <select id="selectAll" resultType="com.ouyanglol.demo.model.User">
        select
        <include refid="Base_Column_List"/>
        from user
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
    delete from user
    where id = #{id,jdbcType=VARCHAR}
  </delete>
    <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.ouyanglol.demo.model.User"
            useGeneratedKeys="true">
    insert into user (userName, sex, age
      )
    values (#{username,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
    <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.ouyanglol.demo.model.User"
            useGeneratedKeys="true">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username != null">
                userName,
            </if>
            <if test="sex != null">
                sex,
            </if>
            <if test="age != null">
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="username != null">
                #{username,jdbcType=VARCHAR},
            </if>
            <if test="sex != null">
                #{sex,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.ouyanglol.demo.model.User">
        update user
        <set>
            <if test="username != null">
                userName = #{username,jdbcType=VARCHAR},
            </if>
            <if test="sex != null">
                sex = #{sex,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                age = #{age,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=VARCHAR}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.ouyanglol.demo.model.User">
    update user
    set userName = #{username,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=VARCHAR}
  </update>
</mapper>

测试类

package com.ouyanglol.demo.controller;

import com.ouyanglol.demo.DemoApplicationTests;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.junit.Assert.*;

/**
 * @author Ouyang
 * @date 18/12/8 21:23
 */
public class UserControllerTest  extends DemoApplicationTests {

    @Autowired
    private UserController userController;

    @Test
    public void list() {
        assertNotNull(userController.list());
    }
}

测试结果

在这里插入图片描述

图(1)

查询没问题,分页插件也成功分页。

项目地址

地址:https://github.com/a252937166/spring-boot-demo
分支:feature/mybatis

参考文章

https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

没有更多推荐了,返回首页