1. 程式人生 > 實用技巧 >五、spring boot開發web應用-更為常用的mybatis

五、spring boot開發web應用-更為常用的mybatis

第三節和第四節分別介紹了傳統的JDBC方式和簡單的JPA方式,但這兩種方式在行業內使用的不多,更常見使用的是mybatis,下面我們就再次改造web應用,讓其使用更為常見的mybatis方式。

1.依賴引入

要使用mybatis框架,首先要引入依賴,但spring boot data沒有包含mybatis的依賴,那我們該如何查詢mybatis的依賴呢?我們可以開啟maven中央倉庫官網https://mvnrepository.com,搜尋mybatis進行查詢,如下:

找到你需要的內容MyBatis Spring Boot Starter,點選進去

進去後,會列出所有版本資訊,選擇你想要的版本(一般不要選擇最新的,而是選擇使用人數最多的)點選進去

進去後,可以根據使用的是maven、Gradle還是其它來檢視依賴,我們的專案使用的是maven,所有拿到的依賴是:

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

2.建立mybatis的xml檔案

(1)在resources在建立mapper資料夾,用於存放xml檔案

(2)配置mapper路徑

在配置檔案application.yml中新增下面配置(如果Mapper.java和Mapper.xml在同一個包下,可以不用設定)

 mybatis:
   # 如果Mapper.java和Mapper.xml在同一個包下,可以不用設定
   mapper-locations: classpath:mapper/*.xml

(3)啟動類新增Mapper全域性掃描(如果不新增,也可以單獨在指定的Dao類加@Mapper註解)

package com.kinglead.demo;
 ​
 import
org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; ​ //@SpringBootApplication註解代表這是一個spring boot應用 //它是一個組合註解 //@SpringBootConfiguration註解將該類宣告為配置類,相當於@Configuration的特殊形式 //@EnableAutoConfiguration啟動spring boot的自動配置 //@ComponentScan啟動元件掃描:將通過@Component、@Controller、@Service這樣註解的類,註冊為spring應用上下文的元件 @MapperScan("com.kinglead.demo.dao") //Mapper全域性掃描 @SpringBootApplication public class SpringInitDemoApplication { ​ /** * @param args 命令列引數 */ public static void main(String[] args) { SpringApplication.run(SpringInitDemoApplication.class, args); } ​ }

(4)建立xml檔案mapper資料夾下

UserDao.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.kinglead.demo.dao.UserDao"><resultMap type="com.kinglead.demo.entity.User" id="TUserMap">
         <result property="id" column="id" jdbcType="INTEGER"/>
         <result property="name" column="name" jdbcType="VARCHAR"/>
         <result property="password" column="password" jdbcType="VARCHAR"/>
     </resultMap>
 ​
 ​
     <!--通過實體作為篩選條件查詢-->
     <select id="queryAll" resultMap="TUserMap">
         select
           id, name, password
         from t_user
         <where>
             <if test="id != null">
                 and id = #{id}
             </if>
             <if test="name != null and name != ''">
                 and name = #{name}
             </if>
             <if test="password != null and password != ''">
                 and password = #{password}
             </if>
         </where>
     </select><!--新增所有列-->
     <insert id="insert" keyProperty="id" useGeneratedKeys="true">
         insert into t_user(name, password)
         values (#{name}, #{password})
     </insert><!--根據使用者名稱和密碼查詢-->
     <select id="findByNameAndPassword" resultMap="TUserMap">
         select id, name, password
         from t_user
         <where>
             <if test="name != null and name != ''">
                 and name = #{name}
             </if>
             <if test="password != null and password != ''">
                 and password = #{password}
             </if>
         </where>
     </select></mapper>

3.改造Dao層,刪除UserRepository,新增UserDao

package com.kinglead.demo.dao;
 ​
 import com.kinglead.demo.entity.User;
 import org.apache.ibatis.annotations.Param;
 import org.springframework.stereotype.Component;
 ​
 import java.util.List;
 ​
 @Component
 public interface UserDao {
 ​
     /**
      * 新增使用者
      */
     int insert(User user);
 ​
     /**
      * 通過使用者名稱和密碼查詢使用者
      */
     User findByNameAndPassword(@Param("name")String name, @Param("password") String password);
 ​
     /**
      * 查詢使用者列表
      */
     List<User> queryAll(User user);
 }

4.改造UserServiceImpl實現類,注入UserDao

package com.kinglead.demo.service.impl;
 ​
 import com.kinglead.demo.dao.UserDao;
 import com.kinglead.demo.entity.User;
 import com.kinglead.demo.service.UserService;
 import org.springframework.stereotype.Service;
 ​
 import javax.annotation.Resource;
 import java.util.List;
 ​
 @Service
 public class UserServiceImpl implements UserService {
 ​
     @Resource
     private UserDao userDao;
 ​
     /**
      * 新增使用者
      */
     @Override
     public int insert(User user) {
         return userDao.insert(user);
     }
 ​
     /**
      * 通過使用者名稱和密碼查詢使用者
      */
     @Override
     public User queryByNameAndPassword(User user) {
         return userDao.findByNameAndPassword(user.getName(), user.getPassword());
     }
 ​
     /**
      * 查詢使用者列表
      */
     @Override
     public List<User> queryAll() {
         return userDao.queryAll(null);
     }
 ​
 }

5.html頁面和Controller保持不變

6.測試

訪問請求http://localhost:8080/user/userList,同樣能返回資料

總結

mybatis是現在行業內最流行框架,也是專案使用最多的框架,大家在實際專案技術選型時,可以大膽的選擇mybatis。另外,由於mybatis在編寫mapper.xml和dao檔案上很費時,為了讓開發人員專注於業務處理,現有很多IDEA外掛能自動生成這些檔案,如:EasyCode,mybatis generate等。筆者使用的是EasyCode,大家根據自己的喜好可以任選一款,至於工具的使用在這就不介紹了,後面有機會單獨發文介紹。

原始碼地址:https://github.com/kinglead2012/myblog