SpringBoot 2.x 整合Mybatis一:基础

转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/80694228
本文出自【赵彦军的博客】

什么是 MyBatis ?

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 JavaPOJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。

官网: http://www.mybatis.org/mybatis-3/zh/index.html

最新的 mybatis-spring-boot-starte 框架版本号详见:

http://jcenter.bintray.com/org/mybatis/spring/boot/mybatis-spring-boot-starter/

添加依赖

本依赖是基于springboot 2.0.2

buildscript {
    ext {
        springBootVersion = '2.0.2.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.yanjun'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    //springboot核心依赖
    compile('org.springframework.boot:spring-boot-starter',
            'org.springframework.boot:spring-boot-starter-web',
             )

    //测试依赖         
    testCompile('org.springframework.boot:spring-boot-starter-test')

    //mysql驱动
    runtime('mysql:mysql-connector-java')  

    //mybatis依赖
    compile 'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0' 
}

然后添加数据库相关配置 application.yml

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    sql-script-encoding: UTF-8

server:
  port: 8032

实战演练

新建实体类 User

package com.yanjun.mybatis.bean;

public class User {

    Integer id;
    String name;
    Integer age;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

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

新建数据库具体操作类 UserMapper

public interface UserMapper {

    @Select("select * from user where name = #{name}")
    List<User> findByName(@Param("name") String name);

    @Insert("insert into user ( name ,age ) values (#{name},#{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Delete("delete from user where id = #{id}")
    int delete(@Param("id") Integer id);

    @Update("update user set age = #{age} where id = #{id}")
    int update(@Param("id") Integer id,@Param("age") Integer age);
}

新建 UserService

package com.yanjun.mybatis.service;

import com.yanjun.mybatis.bean.User;
import com.yanjun.mybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public List get(String name) {
        return userMapper.findByName(name);
    }

    public int insert(String name, Integer age) {
        return userMapper.insert(name, age);
    }

    public int delete(Integer id) {
        return userMapper.delete(id);
    }

    public int update(Integer id, Integer age) {
        return userMapper.update(id, age);
    }

}

新建 UserController

package com.yanjun.mybatis.controller;

import com.yanjun.mybatis.bean.User;
import com.yanjun.mybatis.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("get/{name}")
    public List getUser(@PathVariable("name") String name) {
        return userService.get(name);
    }

    @GetMapping("insert")
    public int insert(@Param("name") String name, @Param("age") Integer age) {
        return userService.insert(name, age);
    }

    @GetMapping("delete")
    public int delete(@Param("id") Integer id) {
        return userService.delete(id);
    }

    @GetMapping("update")
    public int update(@Param("id") Integer id, @Param("age") Integer age) {
        return userService.update(id, age);
    }

}

最后在 MybatisApplication 类里面添加 @MapperScan 注解。

@SpringBootApplication
@MapperScan("com.yanjun.mybatis.mapper")

public class MybatisApplication {

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

最后在 postMan 里面测试对 user 表的增删改查,完全通过。

注意事项

保证数据库操作接口能被 spring 容器扫描到,有两种配置方式:

第一种:在 MybatisApplication 类添加 MapperScan 注解。示例如下:

@SpringBootApplication
@MapperScan("com.yanjun.mybatis.mapper")

public class MybatisApplication {

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

第二种:在 UserMapper 接口上添加 Mapper 注解。示例如下:

package com.yanjun.mybatis.mapper;

import com.yanjun.mybatis.bean.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("select * from user where name = #{name}")
    List findByName(@Param("name") String name);

    @Insert("insert into user ( name ,age ) values (#{name},#{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    @Delete("delete from user where id = #{id}")
    int delete(@Param("id") Integer id);

    @Update("update user set age = #{age} where id = #{id}")
    int update(@Param("id") Integer id,@Param("age") Integer age);
}

在实际开发工作中,我更倾向于第一种方式,因为第一种方式只需要配置一次,就可以了。第二种方式需要多次配置,所以推荐第一种。

总结

本文所有代码已经上传至 GitHub ,分支 1

地址:https://github.com/zyj1609wz/SpringBootMybatis


个人微信号:zhaoyanjun125 , 欢迎关注

你可能感兴趣的:(springboot,SpringBoot应用指南)