springboot整合mybatis

项目代码地址:

https://gitee.com/xuluj/springboot_integrates_mybatis.git

开发环境:

  • 开发工具:Intellij IDEA 2018.3.2
  • springboot: 2.1.2
  • jdk:1.8.0_172
  • maven:3.5.4

 步骤:

1.使用 IDEA建立springboot项目

    File-->New-->Project

2.添加项目依赖 

3.创建数据库及表

CREATE DATABASE mytest;

USE mytest;

CREATE TABLE user(
  user_id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
  user_name VARCHAR(255) NOT NULL ,
  password VARCHAR(255) NOT NULL ,
  age INTEGER
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;

4.application.yml配置文件

server:
  port: 8090
spring:
  datasource:
    username: root
    password: 615610
    url: jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver


## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.xlj.springboot_mybatis.*.entity  # 注意:对应实体类的路径

5.项目文件结构

1.user.java

package com.xlj.springbootmybatis.user.entity;

/**
 * @Author: xlj
 * @Description:
 * @Date: Created in 13:48 2019\2\1 0001
 */
public class User {

    private Integer userId;

    private String userName;

    private String password;

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

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

 2.UserMapper.java

package com.xlj.springbootmybatis.user.mapper;

import com.xlj.springbootmybatis.user.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: xlj
 * @Description:
 * @Date: Created in 13:52 2019\2\1 0001
 */
@Repository
public interface UserMapper {

    User getUserById(Integer userId);

    int addUser(User user);

    int delUserByUserId(Integer userId);

    /**
     * 注:如果使用@Param注解来声明参数时,使用 #{} 或 ${} 的方式都可以
     *    若不使用@Param注解来声明参数,则只能使用#{}
     */
    //@Select("SELECT * FROM USER WHERE user_name like CONCAT('%',${userName},'%')")
    @Select("SELECT user_id userId, user_name userName, password, age FROM USER WHERE user_name like CONCAT('%',#{userName},'%')")
    List<User> getUserByUserName(@Param("userName") String userName);

    List<User> getUserList(User user);

    int updateUserByUserId(@Param("user") User user);
}

4.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.xlj.springbootmybatis.user.mapper.UserMapper">

    <resultMap id="BaseResultMap" type="com.xlj.springbootmybatis.user.entity.User">
        <result column="user_id" jdbcType="INTEGER" property="userId" />
        <result column="user_name" jdbcType="VARCHAR" property="userName" />
        <result column="password" jdbcType="VARCHAR" property="password" />
        <result column="age" jdbcType="INTEGER" property="age" />
    </resultMap>

    <sql id="Base_Column_List">
        user_id userId, user_name userName, password, age
    </sql>

    <insert id="addUser" parameterType="com.xlj.springbootmybatis.user.entity.User">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="userName != null">
                user_name,
            </if>
            <if test="password != null">
                password,
            </if>
            <if test="age != null">
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="userName != null">
                #{userName},
            </if>
            <if test="password != null">
                #{password},
            </if>
            <if test="age != null">
                #{age},
            </if>
        </trim>
    </insert>

    <update id="delUserByUserId" parameterType="java.lang.Integer">
        delete from user where user_id = #{userId}
    </update>

    <select id="getUserById" resultType="com.xlj.springbootmybatis.user.entity.User" parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List"></include>
        from user
        where user_id = #{userId}
    </select>

    <select id="getUserList" parameterType="com.xlj.springbootmybatis.user.entity.User" resultType="com.xlj.springbootmybatis.user.entity.User">
        select
        <include refid="Base_Column_List"></include>
        from user
        where 1 = 1
        <if test="userName != null">
            and user_name like CONCAT('%',#{userName},'%')
        </if>
        <if test="age != null">
            and age = #{age}
        </if>
    </select>

    <update id="updateUserByUserId" parameterType="com.xlj.springbootmybatis.user.entity.User">
        update user
        <set>
            <if test="user.userName != null">
                user_name = #{user.userName},
            </if>
            <if test="user.password != null">
                password = #{user.password},
            </if>
            <if test="user.age != null">
                age = #{user.age},
            </if>
        </set>
        where user_id = #{user.userId}
    </update>
</mapper>

5.Userservice.java

package com.xlj.springbootmybatis.user.service;

import com.github.pagehelper.PageHelper;
import com.xlj.springbootmybatis.user.entity.User;
import com.xlj.springbootmybatis.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: xlj
 * @Description:springboot整合mybatis demo
 * @Date: Created in 14:07 2019\2\1 0001
 */
@Service
public class Userservice {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 感觉用户id查询用户
     * @param userId
     * @return
     */
    public User getUserById(Integer userId){
        return userMapper.getUserById(userId);
    }

    /**
     * Springboot整合JDBC
     * @param userName
     * @param password
     * @param age
     */
    public int saveUser(String userName, String password, Integer age) {
        return jdbcTemplate.update("insert into user(user_name, password, age) value (?, ?, ?)", userName, password, age);
    }

    /**
     * 新建用户
     * @param user
     * @return
     */
    public int addUser(User user){
        return userMapper.addUser(user);
    }

    /**
     * 根据用户id删除用户
     * @param userId
     * @return
     */
    public int delUserByUserId(Integer userId){
        return userMapper.delUserByUserId(userId);
    }

    /**
     * 根据用户名模糊查询用户
     * @param userName
     * @return
     */
    public List<User> getUserByUserName(String userName){
        return userMapper.getUserByUserName(userName);
    }

    /**
     * 用户列表
     */
    public List<User> getUserList(int pageNum, int pageSize, User user){
        PageHelper.startPage(pageNum, pageSize);
        return userMapper.getUserList(user);
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    public int updateUserByUserId(User user){
        return userMapper.updateUserByUserId(user);
    }
}

5.UserController.java

package com.xlj.springbootmybatis.user.controller;

import com.xlj.springbootmybatis.user.entity.User;
import com.xlj.springbootmybatis.user.service.Userservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: xlj
 * @Description:springboot整合mybatis demo
 * @Date: Created in 16:15 2019\1\31 0031
 */
@RestController
public class UserController {

    /**
     * @RequestParam、@PathVariable的区别可自行百度搜索
     */

    @Autowired
    private Userservice userservice;

    @RequestMapping("/saveUser")
    public int saveUser(@RequestParam(value = "userName") String userName,
                         @RequestParam(value = "password") String password, Integer age){
        return  userservice.saveUser(userName, password, age);
    }

    @RequestMapping("/addUser")
    public int addUser(User user){
        return userservice.addUser(user);
    }

    @RequestMapping("/delUserByUserId/{userId}")
    public int delUserByUserId(@PathVariable("userId") Integer id){
        return userservice.delUserByUserId(id);
    }

    @RequestMapping("/updateUserByUserId")
    public int updateUserByUserId(User user){
        return userservice.updateUserByUserId(user);
    }

    @RequestMapping("/getUserById/{userId}")
    public User getUserById(@PathVariable Integer userId){
        return userservice.getUserById(userId);
    }

    @RequestMapping("/getUserByUserName")
    public List<User> getUserByUserName(String userName){
        return userservice.getUserByUserName(userName);
    }

    @RequestMapping("/getUserList")
    public List<User> getUserList(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize,  User user){
        return userservice.getUserList(pageNum, pageSize, user);
    }

}

 

6.springboot启动类

package com.xlj.springbootmybatis;

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

/**
 * @MapperScan("***")这个注解非常的关键,
 * 这个对应了项目中mapper(dao)所对应的包路径,不加则会抛异常
 */
@SpringBootApplication
@MapperScan("com.xlj.springbootmybatis.*.mapper")
public class SpringbootMybatisApplication {

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

6.springboot整合mybatis基本结束,下面可以启动项目,使用postman进行调试了

注:本人也是菜鸟一枚,一边学习一边搭建的简单的框架,第一次写博客,如有问题请多谅解

posted @ 2019-02-13 11:06  徐怼怼  阅读(179)  评论(0编辑  收藏  举报