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

springboot整合mybatis详解_第1张图片

springboot整合mybatis详解_第2张图片

2.添加项目依赖 

springboot整合mybatis详解_第3张图片

springboot整合mybatis详解_第4张图片

springboot整合mybatis详解_第5张图片

springboot整合mybatis详解_第6张图片

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.项目文件结构

springboot整合mybatis详解_第7张图片

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 getUserByUserName(@Param("userName") String userName);

    List getUserList(User user);

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

4.UserMapper.xml





    
        
        
        
        
    

    
        user_id userId, user_name userName, password, age
    

    
        insert into user
        
            
                user_name,
            
            
                password,
            
            
                age,
            
        
        
            
                #{userName},
            
            
                #{password},
            
            
                #{age},
            
        
    

    
        delete from user where user_id = #{userId}
    

    

    

    
        update user
        
            
                user_name = #{user.userName},
            
            
                password = #{user.password},
            
            
                age = #{user.age},
            
        
        where user_id = #{user.userId}
    

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 getUserByUserName(String userName){
        return userMapper.getUserByUserName(userName);
    }

    /**
     * 用户列表
     */
    public List 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 getUserByUserName(String userName){
        return userservice.getUserByUserName(userName);
    }

    @RequestMapping("/getUserList")
    public List 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进行调试了

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

你可能感兴趣的:(java开发,java,springboot,mybatis)