一、項目準備
直接使用上個章節的源碼,Spring Boot教程(八):Spring Boot整合pagehelper分頁外掛程式 二、添加mapper4依賴
<!-- mapper4 --><dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.2</version></dependency>
三、修改啟動類上@MapperScan所在包,注意包路徑!!!
不再採用mybatis的org.mybatis.spring.annotation.MapperScan,而是使用Mapper4的:tk.mybatis.spring.annotation.MapperScan,注意包路徑!!!
package com.songguoliang.springboot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import tk.mybatis.spring.annotation.MapperScan;/** * @Description * @Author sgl * @Date 2018-05-02 14:51 */@SpringBootApplication@MapperScan("com.songguoliang.springboot.mapper")public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
四、建立自己的Mapper基類
建議建立自己的Mapper基類,在自己的Mapper基類裡,我們可以根據我們的項目需要定義適合我們的公用方法。如果不想使用自己建立的,可以直接繼承tk.mybatis.mapper.common.Mapper。
package com.songguoliang.springboot.base;import tk.mybatis.mapper.common.Mapper;import tk.mybatis.mapper.common.MySqlMapper;/** * @Description 自己的Mapper基類,主要不能放到mapper下 * @Author sgl * @Date 2018-05-07 16:57 */public interface BaseMapper<T> extends Mapper<T>,MySqlMapper<T>{}
注意:這個介面不能和表對應的Mapper在同一個表下,即不能在@MapperScan掃描的包裡 五、設定檔修改
在application.properties設定檔中,添加以下配置:
mapper.mappers=com.songguoliang.springboot.base.BaseMappermapper.not-empty=falsemapper.identity=MYSQL
六、修改UserMapper
使UserMapper繼承我們建立的父Mapper:com.songguoliang.springboot.base.BaseMapper
package com.songguoliang.springboot.mapper;import com.github.pagehelper.Page;import com.songguoliang.springboot.base.BaseMapper;import com.songguoliang.springboot.entity.User;/** * @Description * @Author sgl * @Date 2018-05-02 15:02 */public interface UserMapper extends BaseMapper<User> { Page<User> getUsers();}
七、修改UserService
在UserService裡添加一個根據主鍵擷取對象的方法:
public User selectById(long id){ return userMapper.selectByPrimaryKey(id);}
這裡我們直接調用Mapper4內建的selectByPrimaryKey()方法,所以不需要在mapper檔案中寫sql,也不需要在UserMapper中定義方法,這些任務都由Mapper4來做。
可以抽象出來一個BaseService來作為UserService的父類,定義一些我們常用的方法。 八、修改UserController
添加一個服務,用來根據id擷取使用者
@GetMapping("/user/{id}")public User selectUserById(@PathVariable("id") Long id){ return userService.selectById(id);}
九、修改實體類 實體上面添加@Table註解以指定表名,如果表名和實體名一樣,不需要設定,由於我們的表名是tbl_user,所以需要指定。 主鍵上添加@Id註解,聯合主鍵需要主鍵的每個屬性上都加@Id。如果不加該註解,在使用xxxByPrimaryKey方法時,會把所有欄位當成主鍵,即會出現where user_id=? and user_name=? and user_age=?這種條件。
package com.songguoliang.springboot.entity;import javax.persistence.Id;import javax.persistence.Table;/** * @Description * @Author sgl * @Date 2018-05-02 14:59 */@Table(name = "tbl_user")public class User { @Id private Long userId; private String userName; private Integer userAge; //省略getter、setter方法}
十、啟動服務,測試
瀏覽器輸入http://localhost:8080/user/1,得到如下內容:
本文主要是為了說明如何整合Mapper4,對Mapper4的使用,請參考Mapper4作者的GitHub
源碼:
github
碼雲