SpringBoot 2.x 整合Mybatis一:基础

2021年09月15日 阅读数:1
这篇文章主要向大家介绍SpringBoot 2.x 整合Mybatis一:基础,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

 

什么是 MyBatis ?

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

官网mysql

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

添加依赖

本依赖是基于springboot 2.0.2spring

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.ymlsql

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;
    }
}

新建数据库具体操做类 UserMapperapache

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);
}

新建 UserServicespringboot

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<User> 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);
    }

}

新建 UserControllermybatis

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<User> 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 注解。app

@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<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);
}

在实际开发工做中,我更倾向于第一种方式,由于第一种方式只须要配置一次,就能够了。第二种方式须要屡次配置,因此推荐第一种。SpringBoot 2.x 整合Mybatis一:基础_zhaoyanjun