用完spring-data-jpa之後并不是很想用mybatis,但是沒辦法呀,大環境還是mybatis,而且現在mybatis也出了不少插件,我們還是一起看看如何整合mybatis吧
關于整合mybatis有兩種方式,一種是注解方式,另一種是傳統的xml方式
注解方式
先看看引入的依賴
<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.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
sql檔案
CREATE TABLE `test`.`Untitled` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`passwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///test?useSSL=true
spring.datasource.username=root
spring.datasource.password=root
#列印sql語句到控制台
logging.level.com.priv.gabriel.demoformybatis.mapper=debug
User.java
package com.priv.gabriel.demoformybatis.entity;
/**
* Created with Intellij IDEA.
*
* @Author: Gabriel
* @Date: 2018-10-14
* @Description:
*/
public class User {
private long id;
private String username;
private String passwd;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
}
UserMapper.java
package com.priv.gabriel.demoformybatis.mapper;
import com.priv.gabriel.demoformybatis.entity.User;
import org.apache.ibatis.annotations.*;
/**
* Created with Intellij IDEA.
*
* @Author: Gabriel
* @Date: 2018-10-14
* @Description:
*/
@Mapper
public interface UserMapper {
/*注解方式的話直接在方法上寫上對應的sql語句就可以了*/
@Select("select * from user where id = #{id}")
/*如果需要重複使用該Result,給該Results加一個 id 屬性,下面即可使用@ResultMap(id)重複調用*/
@Results(id = "user",value = {
@Result(property = "username",column = "name")
})
User findById(long id);
/*擷取回傳自增id*/
/*id會自動存入user中*/
@Insert("insert into user(name,passwd) values (#{username},#{passwd})")
@Options(useGeneratedKeys = true,keyProperty = "id")
int inertUser(User user);
}
UserController.java
package com.priv.gabriel.demoformybatis.controller;
import com.priv.gabriel.demoformybatis.entity.User;
import com.priv.gabriel.demoformybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created with Intellij IDEA.
*
* @Author: Gabriel
* @Date: 2018-10-14
* @Description:
*/
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public User selectById(@PathVariable long id){
return userMapper.findById(id);
}
@RequestMapping(value = {""},method = RequestMethod.POST)
public String addUser(User user){
userMapper.inertUser(user);
return "現在自增id為"+user.getId();
}
}
在SpringBoot1.x中還需要在啟動類中加入
@MapperScan("mapper所在目錄")
,而在2.x版本中不需要加入就可以自動掃描到mapper了
加入分頁
需要引入pageHelper依賴
<!-- 引入分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
在UserMapper中新增一個查詢所有資訊的方法
@Select("select * from user")
/*調用之前的Results*/
@ResultMap("user")
List<User> listUser();
在Controller中調用
/*擷取分頁資料 包含分頁詳細資訊*/
@RequestMapping(value = "/",method = RequestMethod.GET)
public PageInfo getAll(@RequestParam Integer page, @RequestParam Integer size){
PageHelper.startPage(page,size);
List<User> users = userMapper.listUser();
PageInfo<User> pageInfo = new PageInfo(users);
return pageInfo;
}
/*僅擷取分頁資料
@RequestMapping(value = "/",method = RequestMethod.GET)
public List<User> getAll(@RequestParam Integer page, @RequestParam Integer size){
PageHelper.startPage(page,size);
List<User> users = userMapper.listUser();
return users;
}*/
XML方式
xml方式的話和以前Spring整合mybatis沒有太大的差別,在這裡可以使用Mybatis-Generator自動生成代碼少些一點代碼,其餘的話就不多介紹了
整合通用Mapper
不管是使用注解方式還是XML方式都還是會存在一個什麼都得自己動手的情況,接下來的話,我們整合一個通用的Mapper,在mybatis中體驗jpa的感覺
引用依賴
<!-- 引入通用mapper -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.0.4</version>
</dependency>
繼承BaseMapper
package com.priv.gabriel.demoformybatis.mapper;
import com.priv.gabriel.demoformybatis.entity.User;
import org.apache.ibatis.annotations.Mapper;
import tk.mybatis.mapper.common.BaseMapper;
/**
* Created with Intellij IDEA.
*
* @Author: Gabriel
* @Date: 2018-10-14
* @Description:
*/
@Mapper
public interface UserCommonMapper extends BaseMapper<User> {
}
接着在Controller中調用
@Autowired
private UserCommonMapper mapper;
@RequestMapping("/testCommonMapperForSelectAll")
public List<User> testCommonMapper(){
return mapper.selectAll();
}
關于mybatis的擴充很多,還有像mybatis-plus,關于這個話有時間再說吧,ε=ε=ε=┏(゜ロ゜;)┛