詳解SpringBoot集成MyBatis(注解方式)

MyBatis是支持定制化SQL、存儲(chǔ)過程以及高級映射的優(yōu)秀的持久層框架,避免了幾乎所有的JDBC代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集。spring Boot是能支持快速創(chuàng)建Spring應(yīng)用的Java框架。本文通過一個(gè)例子來學(xué)習(xí)Spring Boot如何集成MyBatis,而且過程中不需要XML配置。

創(chuàng)新互聯(lián)公司是一家專業(yè)的成都網(wǎng)站建設(shè)公司,我們專注做網(wǎng)站、成都網(wǎng)站建設(shè)、網(wǎng)絡(luò)營銷、企業(yè)網(wǎng)站建設(shè),外鏈,一元廣告為企業(yè)客戶提供一站式建站解決方案,能帶給客戶新的互聯(lián)網(wǎng)理念。從網(wǎng)站結(jié)構(gòu)的規(guī)劃UI設(shè)計(jì)到用戶體驗(yàn)提高,創(chuàng)新互聯(lián)力求做到盡善盡美。

創(chuàng)建數(shù)據(jù)庫

本文的例子使用MySQL數(shù)據(jù)庫,首先創(chuàng)建一個(gè)用戶表,執(zhí)行sql語句如下:

CREATE TABLE IF NOT EXISTS user (
 `id` INT(10) NOT NULL AUTO_INCREMENT,
 `name` VARCHAR(50) NULL DEFAULT NULL ,
 `age` INT(2) NOT NULL ,
 PRIMARY KEY (id)
)

工程目錄結(jié)構(gòu)與依賴配置

首先新建一個(gè)Maven工程,并配置Pom依賴,本例中所用到的依賴如下:

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.2.RELEASE</version>
  <relativePath />
</parent>

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.40</version>
  </dependency>
</dependencies>

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>

然后創(chuàng)建一下工程目錄結(jié)構(gòu),如下圖所示:

詳解Spring Boot集成MyBatis(注解方式)

代碼文件內(nèi)容

0. 創(chuàng)建配置文件——application.properties

寫入一下內(nèi)容:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

1. 創(chuàng)建POJO——entity/User.java

這是一個(gè)POJO,包含了id, name, age三個(gè)屬性,代碼如下:

package com.xyz.dbtest.entity;
public class User {
  private int id;
  private String name;
  private int age;

  public int getId() {  return id;  }

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

  public String getName() {  return name;  }

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

  public int getAge() {  return age;  }

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

2. 創(chuàng)建一個(gè)數(shù)據(jù)層接口——service/UserService.java

這是一個(gè)Mapper類,代碼如下:

package com.xyz.dbtest.dao;

import com.xyz.dbtest.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper //1
public interface UserDao {
  @Results({ //2
      @Result(property = "id", column = "id"), //2
      @Result(property = "name", column = "name"),
      @Result(property = "age", column = "age")
  })
  @Select("SELECT * FROM user WHERE age = #{age}") //3
  List<User> get(int age);

  @Insert("INSERT INTO user(name, age) VALUES (#{name}, #{age})") //3
  void insert(User user);
}

//1 @Mapper將UserDao聲明為一個(gè)Mapper接口
//2 @Results是結(jié)果映射列表,@Result中property是User類的屬性名,colomn是數(shù)據(jù)庫表的字段名
//3 @Select, @Insert 分別代表了執(zhí)行的真實(shí)SQL

3. 創(chuàng)建一個(gè)用戶服務(wù)——service/UserService.java

這是一個(gè)服務(wù)類Bean,提供三個(gè)函數(shù)功能,代碼如下:

package com.xyz.dbtest.service;

import com.xyz.dbtest.dao.UserDao;
import com.xyz.dbtest.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service //聲明成一個(gè)spring bean
public class UserService {

  @Autowired //連接到UserDao Bean
  private UserDao userDao;

  public String show() {
    return "Hello World!";
  }

  public List<User> showDao(int age) {
    return userDao.get(age);
  }

  public String insert(String name, int age) { //插入一條記錄
    User user = new User();
    user.setName(name);
    user.setAge(age);
    userDao.insert(user);
    return "Insert ( \""+name+"\", age"+age+") OK!";
  }
}

4. 常見一個(gè)Web Controller——controller/UserController.java

這是一個(gè)Spring Web的Controller類,引入了spring-boot-starter-web依賴,代碼如下:

package com.xyz.dbtest.controller;

import com.xyz.dbtest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController //聲明為一個(gè)Restful的Controller
public class UserController {
  @Autowired //自動(dòng)連接到UserService Bean
  private UserService userService;

  @RequestMapping(value = "/show")
  public String show() {
    return userService.show();
  }

  @RequestMapping(value = "/showDao")
  public Object showDao(int age) {
    return userService.showDao(age);
  }

  @RequestMapping(value="/insert")
  public String insert(String name, int age) {
    return userService.insert(name, age);
  }
}

5. 創(chuàng)建啟動(dòng)類——main/StartApp.java

這是一個(gè)spring boot啟動(dòng)類。代碼如下:

package com.xyz.dbtest.main;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.xyz.dbtest") //1
@MapperScan(basePackages = "com.xyz.dbtest.dao") //2
public class StartApp {
  public static void main(String[] args) {
    SpringApplication.run(StartApp.class, args);
  }
}

//1 由于StartApp類位于基礎(chǔ)包的自包中,因此需要設(shè)置scanBasePackage
//2 設(shè)置Mapper接口所在的包

運(yùn)行結(jié)果

運(yùn)行Sql語句創(chuàng)建數(shù)據(jù)庫表后,運(yùn)行StartApp類。啟動(dòng)成功如下圖所示

詳解Spring Boot集成MyBatis(注解方式)

測試show服務(wù),結(jié)果如下:

詳解Spring Boot集成MyBatis(注解方式)

測試showDao服務(wù),在輸入U(xiǎn)RL時(shí)需要將參數(shù)打包進(jìn)url,結(jié)果如下:
不帶參數(shù)時(shí),訪問錯(cuò)誤:

詳解Spring Boot集成MyBatis(注解方式)

帶參數(shù)時(shí),訪問成功,由于數(shù)據(jù)庫中沒有記錄,所以結(jié)果是一個(gè)空列表:

詳解Spring Boot集成MyBatis(注解方式)

測試insert服務(wù)

詳解Spring Boot集成MyBatis(注解方式)

詳解Spring Boot集成MyBatis(注解方式)

再次測試showDao服務(wù)

詳解Spring Boot集成MyBatis(注解方式)

結(jié)語

通過本文的例子可以看出,使用Spring boot集成MyBatis幾乎不用任何配置工作,能有效加快開發(fā)效率!

代碼庫地址:github地址

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

標(biāo)題名稱:詳解SpringBoot集成MyBatis(注解方式)
鏈接地址:http://muchs.cn/article14/pipide.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供小程序開發(fā)、電子商務(wù)品牌網(wǎng)站設(shè)計(jì)、Google網(wǎng)站導(dǎo)航、網(wǎng)站排名

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司