1. 程式人生 > >SpringBoot+Mybatis整合(一)

SpringBoot+Mybatis整合(一)

Spring boot的優點

  • 輕鬆建立獨立的Spring應用程式。
  • 內嵌Tomcat、jetty等web容器,不需要部署WAR檔案。
  • 提供一系列的“starter” 來簡化的Maven配置。
  • 開箱即用,儘可能自動配置Spring。

說明:本文章主要是SpringBoot+Mybatis註解整合,其中主要是框架的搭建,簡單的增刪改查案例和簡單動態sql查詢。

正題:只需要3步就完成框架搭建

首先說明一下工程目錄結構:

1.配置pom.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.example</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>MySpringBoot</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.3.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version>
      <mysql-connector.version>5.1.39</mysql-connector.version>
      <java.version>1.8</java.version>
   </properties>
   <dependencies>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
          </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      <!--mybatis依賴包-->
       <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
          <version>${mybatis-spring-boot.version}</version>
       </dependency>
      <!--mysql資料庫依賴包-->
       <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>${mysql-connector.version}</version>
       </dependency>
      <!--lombok自動生成實體類中的getset方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>
    </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

2.application.properties檔案配置

server.port=9090
#檢視層控制 用mvc方式訪問templates下的HTML
#訪問字尾  spring.mvc.view.suffix=.html類似Springmvc中的檢視資料夾
spring.mvc.view.prefix=classpath:/templates/
#訪問字尾  spring.mvc.view.suffix=.html類似Springmvc中的.jsp
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/static/**
#開發時關閉快取,不然沒法看到實時頁面
spring.thymeleaf.cache=false
#thymeleaf這樣配置就可以直接訪問static下的HTML(和mvc訪問方式二選一)
spring.thymeleaf.prefix = classpath:/static/
spring.thymeleaf.suffix = .html

spring.datasource.url=jdbc:mysql://192.168.1.9:3306/test_demo_lqw?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=zp123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.typeAliasesPackage=com.example.demo.model 

#驗證連線的有效性
spring.datasource.primary.test-while-idle=true
#獲取連線時候驗證,會影響效能
spring.datasource.primary.test-on-borrow=false
#在連線歸還到連線池時是否測試該連線
spring.datasource.primary.test-on-return=false
spring.datasource.primary.validation-query=SELECT 1 FROM DUAL
#空閒連接回收的時間間隔,與test-while-idle一起使用,設定5分鐘
spring.datasource.primary.time-between-eviction-runs-millis=300000
#連線池空閒連線的有效時間 ,設定30分鐘
spring.datasource.primary.min-evictable-idle-time-millis=1800000
spring.datasource.primary.initial-size=5
#指定連線池中最大的活躍連線數.
spring.datasource.primary.max-active=50
#指定連線池等待連線返回的最大等待時間,毫秒單位.
spring.datasource.primary.max-wait=60000
#指定必須保持連線的最小值
spring.datasource.primary.min-idle=5
#開啟駝峰命名轉換
mybatis.configuration.map-underscore-to-camel-case=true
#sql列印控制檯
logging.level.com.example.demo.mapper=debug

3.入口MySpringBootApplication.java檔案

package com.example.demo;

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

@MapperScan("com.example.demo.mapper")
@SpringBootApplication//(exclude = {DataSourceAutoConfiguration.class})
public class MySpringBootApplication {
   public static void main(String[] args) {
      SpringApplication.run(MySpringBootApplication.class, args);
   }
}

到此我們的SpringBoot+Mybatis整合已經搭建完成。

接下來是Demo 演示了,findUserByQuery方法是動態sql案例

控制層 TestController

package com.example.demo.controller;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * Created by 李慶偉 on 2018/7/24.
 */
@RestController
public class TestController {

    @Autowired
    private UserService userService;


    @RequestMapping("/hello")
    public String hello (){
        return "this is HelloWord";
    }

    /**
     * 根據id獲取user物件
     * @return
     */
    @RequestMapping("/getUserById")
    public User getUserById(){
        String id = "0";
        return userService.getUserById(id);
    }

    /**
     * 根據id獲取Map物件
     * @return
     */
    @RequestMapping("/getUserMap")
    public Map<String,Object> getUserMap(){
        String id = "0";
        return userService.getUserMap(id);
    }

    /**
     * 新增方法
     * @param
     * @return String
     */
    @RequestMapping("/save")
    public String save (){
        User user =  new User();
        user.setId("111");
        user.setUserName("XXXX");
        int num = userService.save(user);
        if(num == 1){
            return "save sucess";
        }else {
            return "save error";
        }
    }


    /**
     * 修改方法
     * @param
     * @return String
     */
    @RequestMapping("/update")
    public String update (){
        User user =  new User();
        user.setId("111");
        user.setUserName("1111111");
        int num = userService.update(user);
        if(num == 1){
            return "update sucess";
        }else {
            return "update error";
        }
    }

    /**
     * 刪除
     * @param
     * @return String
     */
    @RequestMapping("/delete")
    public String delete (){
        User user =  new User();
        user.setId("444");
        int num = userService.delete(user);
        if(num == 1){
            return "delete sucess";
        }else {
            return "delete error";
        }
    }

    /**
     * 動態sql的查詢
     * dao介面中是不能寫實現的,所以這裡借用內部類來生成動態SQL。增改刪也有對應的@InsertProvider、@UpdateProvider、     @DeleteProvider
     * @param
     * @return
     */
    @RequestMapping("/findUserByQuery")
    public List<User> findUserByQuery(){
        User user =  new User();
        user.setId("0");
        //user.setUserName("0");
        user.setUserName("張三0");
        List<User> userList = userService.findUserByQuery(user);
        return userList;
    }

}

業務層介面UserService

package com.example.demo.service;

import com.example.demo.model.User;

import java.util.List;
import java.util.Map;

/**
 * Created by 李慶偉 on 2018/7/24.
 */
public interface UserService {
    /**
     * 通過id獲取使用者
     * @return
     */
    public User getUserById(String id);

    /**
     * 根據id獲取Map物件
     * @return
     */
    public Map<String,Object> getUserMap(String id);

    /**
     * 新增方法
     * @param user
     * @return
     */
    public int save(User user);

    /**
     * 修改方法
     * @param user
     * @return
     */
    public int update(User user);

    /**
     * 刪除
     * @param user
     * @return
     */
    public int delete(User user);

    /**
     * 動態sql的查詢
     * dao介面中是不能寫實現的,所以這裡借用內部類來生成動態SQL。增改刪也有對應的@InsertProvider、@UpdateProvider、@DeleteProvider
     * @param user
     * @return
     */
    public List<User> findUserByQuery(User user);
}

業務層介面實現類UserServiceImpl

package com.example.demo.service.impl;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by 李慶偉 on 2018/7/24.
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;
    /**
     * 通過id獲取使用者
     * @return
     */
    @Override
    public User getUserById(String id) {
        return userMapper.getUserById(id);
    }

    /**
     * 根據id獲取Map物件
     * @return
     */
    public Map<String,Object> getUserMap(String id){
        return userMapper.getUserMap(id);
    }

    /**
     * 新增方法
     * @param user
     * @return
     */
    public int save(User user){
        return userMapper.save(user);
    }

    /**
     * 修改方法
     * @param user
     * @return
     */
    public int update(User user){
        return userMapper.update(user);
    }

    /**
     * 刪除
     * @param user
     * @return
     */
    @Transactional
    public int delete(User user){
        /*
        User addUser = new User();
        addUser.setId("3333");
        addUser.setUserName("3333");
        userMapper.save(addUser);
        int a = 1/0;
        */
        return userMapper.delete(user);
    }

    /**
     * 動態sql的查詢
     * dao介面中是不能寫實現的,所以這裡借用內部類來生成動態SQL。增改刪也有對應的@InsertProvider、@UpdateProvider、@DeleteProvider
     * @param user
     * @return
     */
    public List<User> findUserByQuery(User user){
        return userMapper.findUserByQuery(user);
    }
}

資料層UserMapper

package com.example.demo.mapper;

import com.example.demo.model.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

import static org.apache.ibatis.jdbc.SqlBuilder.SELECT;

/**
 * Created by 李慶偉 on 2018/7/24.
 */
@Repository
public interface UserMapper {
    /**
     * 通過查詢能夠直接對映到實體類中的屬性是因為  配置了駝峰模式
     *
     * @param id
     * @return
     */
    @Select("select id,user_name from user_t where id = #{id}")
    public User getUserById(String id);

    /**
     * 不配置駝峰模式
     * @param
     * @return
     */
    /*@Select("select id,user_name from user_t where id = #{id}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "userName", column = "user_name") })
    public User getUserById(String id);*/


    /**
     * 返回map
     *
     * @param id
     * @return
     */
    @Select("select id,user_name as userName from user_t where id = #{id}")
    public Map<String, Object> getUserMap(String id);

    /**
     * 新增方法
     *
     * @param user
     * @return
     */
    @Insert("insert into user_t(id, user_name) VALUES(#{id}, #{userName})")
    int save(User user);

    /**
     * 修改方法
     *
     * @param user
     * @return
     */
    @Update("update user_t SET user_name=#{userName} WHERE id=#{id}")
    int update(User user);

    /**
     * 刪除
     *
     * @param user
     * @return
     */
    @Delete("delete from user_t WHERE id =#{id}")
    int delete(User user);

    /**
     * 動態sql的查詢 三中方法實現,1.字串拼接  2.內部類中兩種
     * dao介面中是不能寫實現的,所以這裡借用內部類來生成動態SQL。增改刪也有對應的@InsertProvider、@UpdateProvider、@DeleteProvider
     * @param user
     * @return
     */

    //@Select("<script>select * from user_t <if test=\"id !=null \">where id = #{id} </if></script>")
    //@SelectProvider(type = UserDaoProvider.class, method = "findOne")
    @SelectProvider(type = UserDaoProvider.class, method = "findTwo")
    public List<User> findUserByQuery(User user);

    class UserDaoProvider {
        public String findOne(User user) {
            String sql = "SELECT * FROM user_t where 1=1";
            if (user.getUserName() != null) {
                sql += " and user_name = #{userName}";
            }
            if(user.getId()!=null){
                sql += " and id = #{id}";
            }
            return sql;
        }

        public String findTwo(User user) {
            return new SQL(){{
                SELECT("id,user_name");
                FROM("user_t");
                if(user.getId()!=null){
                    WHERE("id = #{id}");
                }
                if(user.getUserName()!=null){
                    WHERE("user_name = #{userName}");
                }
                //從這個toString可以看出,其內部使用高效的StringBuilder實現SQL拼接
            }}.toString();

        }
    }
}

實體類User

package com.example.demo.model;

import lombok.Data;

/**
 * Created by 李慶偉 on 2018/7/24.
 */

@Data
public class User {
    private String id;
    private String userName;
}

資料庫表user_t

到此Demo也完成了

每天進步一點點。。。。。