Spring Boot 揭祕與實戰(二) 資料儲存篇 - MyBatis整合

樑桂釗發表於2016-12-20

本文講解Spring Boot基礎下,如何整合MyBatis框架,編寫資料訪問。
原文地址:Spring Boot 揭祕與實戰(二) 資料儲存篇 - MyBatis整合
部落格地址:blog.720ui.com/

環境依賴

修改 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.1.1</version>
</dependency>複製程式碼

新增mysql依賴。

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.35</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.0.14</version>
</dependency>複製程式碼

資料來源

方案一 使用 Spring Boot 預設配置

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

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_db?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root複製程式碼

方案二 手動建立

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

# mysql
source.driverClassName = com.mysql.jdbc.Driver
source.url = jdbc:mysql://localhost:3306/springboot_db?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
source.username = root
source.password = root複製程式碼

通過 Java Config 建立 dataSource 和jdbcTemplate 。

@Configuration
@EnableTransactionManagement
@PropertySource(value = {"classpath:config/source.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指令碼。

CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `springboot_db`;

DROP TABLE IF EXISTS `t_author`;

CREATE TABLE `t_author` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '使用者ID',
  `real_name` varchar(32) NOT NULL COMMENT '使用者名稱稱',
  `nick_name` varchar(32) NOT NULL COMMENT '使用者匿名',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;複製程式碼

MyBatis整合

方案一 通過註解的方式

實體物件

public class Author {
    private Long id;
    @JSONField(name="real_name")
    private String realName;
    @JSONField(name="nick_name")
    private String nickName;

    // SET和GET方法
}複製程式碼

DAO相關

@Mapper
public interface AuthorMapper {

    @Insert("insert into t_author(real_name, nick_name) values(#{real_name}, #{nick_name})")
    int add(@Param("realName") String realName, @Param("nickName") String nickName);

    @Update("update t_author set real_name = #{real_name}, nick_name = #{nick_name} where id = #{id}")
    int update(@Param("real_name") String realName, @Param("nick_name") String nickName, @Param("id") Long id);

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

    @Select("select id, real_name as realName, nick_name as nickName from t_author where id = #{id}")
    Author findAuthor(@Param("id") Long id);

    @Select("select id, real_name as realName, nick_name as nickName from t_author")
    List<Author> findAuthorList();
}複製程式碼

Service相關

@Service
public class AuthorService {
    @Autowired
    private AuthorMapper authorMapper;

    public int add(String realName, String nickName) {
        return this.authorMapper.add(realName, nickName);
    }
    public int update(String realName, String nickName, Long id) {
        return this.authorMapper.update(realName, nickName, id);      
    }
    public int delete(Long id) {
        return this.authorMapper.delete(id);
    }
    public Author findAuthor(Long id) {
        return this.authorMapper.findAuthor(id);
    }
    public List<Author> findAuthorList() {
        return this.authorMapper.findAuthorList();
    }
}複製程式碼

Controller相關

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

@RestController("mybatis.authorController")
@RequestMapping(value="/data/mybatis/author")
@MapperScan("com.lianggzone.springboot.action.data.mybatis.dao")
public class AuthorController {

  @Autowired
  private AuthorService authorService;
  /**
   * 查詢使用者列表
   */
  @RequestMapping(method = RequestMethod.GET)
  public Map<String,Object> getAuthorList(HttpServletRequest request) {        
    List<Author> authorList = this.authorService.findAuthorList();
    Map<String,Object> param = new HashMap<String,Object>();
    param.put("total", authorList.size());
    param.put("rows", authorList);
    return param;
  }
  /**
   * 查詢使用者資訊
   */
  @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
    Author author = this.authorService.findAuthor(userId);
    if(author == null){
        throw new RuntimeException("查詢錯誤");
    }
    return author;
  }

  /**
   * 新增方法
   */
  @RequestMapping(method = RequestMethod.POST)
  public void add(@RequestBody JSONObject jsonObject) {
    String userId = jsonObject.getString("user_id");
    String realName = jsonObject.getString("real_name");
    String nickName = jsonObject.getString("nick_name");

    try{
        this.authorService.add(realName, nickName);
    }catch(Exception e){
        e.printStackTrace();
        throw new RuntimeException("新增錯誤");
    }
  }
  /**
   * 更新方法
   */
  @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
    public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
    Author author = this.authorService.findAuthor(userId);
    String realName = jsonObject.getString("real_name");
    String nickName = jsonObject.getString("nick_name");

    try{
        this.authorService.update(realName, nickName, author.getId());
    }catch(Exception e){
        e.printStackTrace();
        throw new RuntimeException("更新錯誤");
    } 
  }
  /**
   * 刪除方法
   */
  @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
    public void delete(@PathVariable Long userId) {
    try{
        this.authorService.delete(userId);
    }catch(Exception e){
        throw new RuntimeException("刪除錯誤");
    }
  }
}複製程式碼

方案二 通過配置檔案的方式

實體物件

public class Author {
    private Long id;
    @JSONField(name="real_name")
    private String realName;
    @JSONField(name="nick_name")
    private String nickName;

    // SET和GET方法
}複製程式碼

配置相關

在 src/main/resources/mybatis/AuthorMapper.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.lianggzone.springboot.action.data.mybatis.dao.AuthorMapper2">

    <!-- type為實體類Student,包名已經配置,可以直接寫類名 -->
    <resultMap id="authorMap" type="Author">
        <id property="id" column="id" />
        <result property="realName" column="real_name" />
        <result property="nickName" column="nick_name" />
    </resultMap>

    <select id="findAuthor" resultMap="authorMap" resultType="Author">
        select id, real_name, nick_name from t_author where id = #{id}
    </select>
</mapper>複製程式碼

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

mybatis.mapper-locations=classpath*:mybatis/*Mapper.xml
mybatis.type-aliases-package=com.lianggzone.springboot.action.data.mybatis.entity複製程式碼

DAO相關

public interface AuthorMapper2 { 
    Author findAuthor(@Param("id") Long id); 
}複製程式碼

Service相關

@Service
public class AuthorService2 {
    @Autowired
    private AuthorMapper2 authorMapper;

    public Author findAuthor(Long id) {
        return this.authorMapper.findAuthor(id);
    }
}複製程式碼

Controller相關

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

@RestController("mybatis.authorController2")
@RequestMapping(value="/data/mybatis/author2")
@MapperScan("com.lianggzone.springboot.action.data.mybatis.dao")
public class AuthorController2 { 
  @Autowired
  private AuthorService2 authorService; 
  /**
   * 查詢使用者資訊
   */
  @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
    Author author = this.authorService.findAuthor(userId);
    if(author == null){
        throw new RuntimeException("查詢錯誤");
    }
    return author;
  }
}複製程式碼

總結

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

原始碼

相關示例完整程式碼: springboot-action

(完)

更多精彩文章,盡在「服務端思維」微信公眾號!

Spring Boot 揭祕與實戰(二) 資料儲存篇 - MyBatis整合

相關文章