1. 程式人生 > >第三篇:Spring Boot整合MyBatis

第三篇:Spring Boot整合MyBatis

本文主要講解如何在Spring Boot下整合MyBatis並訪問資料庫。MyBatis 是一款優秀的持久層框架,它支援定製化 SQL、儲存過程以及高階對映。(如不瞭解點選前往

環境依賴

修改 POM 檔案,新增mybatis-spring-boot-starter依賴。值得注意的是,可以不新增spring-boot-starter-jdbc。因為,mybatis-spring-boot-starter依賴中存在spring-boot-starter-jdbc。

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

新增mysql依賴。

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</
scope
>
</dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.29</version> </dependency>

資料來源

使用 Spring Boot 預設配置

在 src/main/resources/application.yml中配置資料來源資訊。

spring:
  datasource:
    # 使用druid資料來源
type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/springboot_test?useUnicode=true&characterEncoding=UTF-8 username: root password: root

手動建立

在 src/main/resources/config/dataSource.properties 中配置資料來源資訊。

# mysql
source.driverClassName=com.mysql.jdbc.Driver
source.url=jdbc:mysql://localhost:3306/springboot_test?useUnicode=true&characterEncoding=UTF-8
source.username=root
source.password=root

通過 BeanConfig 建立 dataSource 和jdbcTemplate 。

@Configuration
@EnableTransactionManagement
@PropertySource(value = {"classpath:config/dataSource.properties"})
public class BeanConfig {

    @Autowired
    private Environment env;

    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(env.getProperty("source.driverClassName").trim());
        dataSource.setUrl(env.getProperty("source.url").trim());
        dataSource.setUsername(env.getProperty("source.username").trim());
        dataSource.setPassword(env.getProperty("source.password").trim());
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource());
        return jdbcTemplate;
    }
}

指令碼初始化

先初始化需要用到的SQL指令碼。

-- 匯出 springboot_test 的資料庫結構
CREATE DATABASE IF NOT EXISTS `springboot_test` 
USE `springboot_test`;

-- 匯出  表 springboot_test.user 結構
CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL,
  `name` varchar(50) COLLATE utf8_bin DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- 正在匯出表  springboot_test.user 的資料:~0 rows (大約)

INSERT INTO `user` (`id`, `name`, `age`) VALUES
	(1, 'chenjay', 22),
	(2, 'lucy', 19),
	(3, 'mary', 35);

MyBatis整合

通過註解的方式

實體物件

public class User {
    private int id;
    private String name;
    private int age;
    // SET和GET方法
}

DAO相關

@Mapper
public interface UserDao {
    @Insert("insert into user(id, name, age) values(#{id}, #{name}, #{age})")
    int add(@Param("id") int id, @Param("name") String name, @Param("age") int age);

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

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

    @Select("select id, name, age from user where id = #{id}")
    User findUser(@Param("id") int id);

    @Select("select id, name, age from user")
    List<User> findUserList();
}

Service相關

@Service
@Service
public class UserService {

    @Autowired
    private UserDao userDao;

    public int add(int id,String name,int age) {
        return userDao.add(id, name, age);
    }
    public int update(String name,int age, int id) {
        return userDao.update(name, age, id);
    }
    public int delete(int id) {
        return userDao.delete(id);
    }
    public User findUser(int id) {
        return userDao.findUser(id);
    }
    public List<User> findUserList() {
        return userDao.findUserList();
    }
}

Controller相關
為了展現效果,我們先定義一組簡單的 RESTful API 介面進行測試。

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping(value = "/list")
    public List<User> findUserList() {
        return userService.findUserList();
    }

    @GetMapping(value = "/{id}")
    public User findUser(@PathVariable("id") int id) {
        return userService.findUser(id);
    }

    @PutMapping(value = "/{id}")
    public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
                                @RequestParam(value = "age", required = true) int age) {
        if (0 < userService.update(name, age, id)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @DeleteMapping(value = "/{id}")
    public String delete(@PathVariable(value = "id") int id) {
        if (0 < userService.delete(id)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @PostMapping(value = "/add")
    public String postAccount(@RequestParam(value = "id") int id, @RequestParam(value = "name") String name,
                              @RequestParam(value = "age") int age) {
        if (0 < userService.add(id, name, age)) {
            return "success";
        } else {
            return "fail";
        }
    }
}

通過Postman測試:

  • 查詢使用者
    在這裡插入圖片描述
  • 查詢列表
    在這裡插入圖片描述
  • 新增使用者
    在這裡插入圖片描述
  • 修改使用者 在這裡插入圖片描述
  • 刪除使用者
    在這裡插入圖片描述
  • 最後再檢視使用者列表
    在這裡插入圖片描述
    可以從上圖看出刪除使用者,修改使用者,新增使用者都對資料庫做出了修改。

通過配置檔案的方式

Mapper檔案配置
在 src/main/resources/mapper/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.chenjie.springboot.learn.dao.UserDao2">
    <insert id="add" parameterType="user">
        insert into user(id, name, age)
          values(#{id},  #{name}, #{age})
    </insert>
    <update id="update" parameterType="user">
        update user
        <set>
            <if test="name != null ">
                name = #{name},
            </if>
            <if test="age != null ">
                age = #{age},
            </if>
        </set>
        where
          id = #{id}
    </update>
    <delete id="delete">
        delete from user where id = #{id}
    </delete>
    <select id="findUserList" resultType="user">
        select * from user
    </select>
    <select id="findUser" resultType="user">
        select * from user where id = #{id}
    </select>
</mapper>

在 src/main/resources/application.yml中配置資料來源資訊。

mybatis:
  mapper-locations: classpath*:mapper/*.xml
  type-aliases-package: com.chenjie.springboot.learn.entity
  • mybatis.mapper-locations來指明mapper的xml檔案存放位置,我是放在resources/mapper檔案下的。
  • mybatis.type-aliases-package來指明和資料庫對映的實體的所在包。

DAO相關

@Mapper
public interface UserDao2 {
    int add(User user);

    int update(User user);

    int delete(int id);

    User findUser(@Param("id") int id);

    List<User> findUserList();
}

Service相關

@Service
public class UserService2 {

    @Autowired
    private UserDao2 userDao;

    public int add(int id,String name,int age) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        return userDao.add(user);
    }
    public int update(String name,int age, int id) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        return userDao.update(user);
    }
    public int delete(int id) {
        return userDao.delete(id);
    }
    public User findUser(int id) {
        return userDao.findUser(id);
    }
    public List<User> findUserList() {
        return userDao.findUserList();
    }
}

Controller相關

@RestController
@RequestMapping("/user2")
public class UserController2 {

    @Autowired
    private UserService2 userService;

    @GetMapping(value = "/list")
    public List<User> findUserList() {
        return userService.findUserList();
    }

    @GetMapping(value = "/{id}")
    public User findUser(@PathVariable("id") int id) {
        return userService.findUser(id);
    }

    @PutMapping(value = "/{id}")
    public String updateAccount(@PathVariable("id") int id, @RequestParam(value = "name", required = true) String name,
                                @RequestParam(value = "age", required = true) int age) {
        if (0 < userService.update(name, age, id)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @DeleteMapping(value = "/{id}")
    public String delete(@PathVariable(value = "id") int id) {
        if (0 < userService.delete(id)) {
            return "success";
        } else {
            return "fail";
        }
    }

    @PostMapping(value = "/add")
    public String postAccount(@RequestParam(value = "id") int id, @RequestParam(value = "name") String name,
                              @RequestParam(value = "age") int age) {
        if (0 < userService.add(id, name, age)) {
            return "success";
        } else {
            return "fail";
        }
    }
}

通過Postman測試:

查詢列表
在這裡插入圖片描述
這裡就不做其他測試,此測試旨在測試MyBatis可以使用簡單的XML來配置和對映原生資訊

總結

上面這個簡單的案例,讓我們看到了 Spring Boot 整合 MyBatis 框架的大概流程。那麼,複雜的場景,大家可以參考使用一些比較成熟的外掛,例如com.github.pagehelper、mybatis-generator-maven-plugin等。

原始碼下載:https://github.com/chenjary/SpringBoot