1. 程式人生 > >spring boot (四)mybatis

spring boot (四)mybatis

開發十年,就只剩下這套架構體系了! >>>   

上回說到web應用的前半截,還沒有持久層,一個沒有持久層的web應用不是完整的,現在我們就來使用mybatis連線MySQL儲存資料,如果還沒有安裝MySQL資料庫,百度安裝(手動滑稽)。

資料庫配置

	<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis 配置

	<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
#mybatis xml 檔案目錄
mybatis.mapper-locations=classpath:mapper/*.xml
#mybatis 介面包
mybatis.type-aliases-package=cn.le.dao

#列印SQL語句
#logging.level.org.springframework=WARN
#指定mybatis需要列印的SQL對應的mapper
#logging.level.cn.le.inf.UserMapper=DEBUG
#日誌輸出
#logging.file=logs/spring-boot-logging.log

擼碼

首先我們編寫對應的介面和xml檔案

[@Mapper](https://my.oschina.net/u/1452465) // 對映mybatis實現
public interface UserDAO {
    //[@Param](https://my.oschina.net/u/2303379) 對映引數
    UserPO login(@Param("name")String name,@Param("pwd")String pwd);
}
 <sql id="column"> /*資料庫列名對映*/
        name as name, pwd as pwd
    </sql>

    <select id="login" resultType="cn.le.beans.po.UserPO">
        select <include refid="column"/> from user where name = #{name} and pwd = #{pwd}
    </select>
[@Service](https://my.oschina.net/service)
public class UserService {
    @Autowired
    private UserDAO userDAO;

    public UserPO login(UserDTO dto){
        return userDAO.login(dto.getName(),dto.getPwd());
    }
}

pagehelper 分頁

在使用mybatis的時候有一個分頁的好幫手pagehelper,現在我們來整合pagehelper。

	<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

修改service查詢

public Page findUser(PageDTO dto){
        //老版本分頁到最後資料庫沒有資料時會返回最後一頁的資料,如果希望返回空資料,reasonable設定為false
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        return (Page) userDAO.findUser();
    }

mybatis還有一種全註解模式,但是個人建議不這樣用,mybatis介面中寫了太多了sql,看著難受(手動滑稽)

---------------程式碼 git 地址 https://gitee.com/distant/spr