SpringBoot(五):SpringBoot整合MyBatis
怎麼說了,寫部落格雖然是一件很費時間的事情,而且還是個菜鳥,但是如果寫的東西能夠幫助到別人,還是值得開心的。
回顧:
上篇寫了JdbcTemplate,但是想到使用Mybatis,JPA的人估計不少,所以這篇寫一下SpringBoot整合Mybatis,JPA的話以後有時間再弄,因為自己也沒用過。
一、資料準備
其實還是上篇的,以防有人是直接看這篇的,就還是貼出來吧。
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`username` varchar(50) NOT NULL COMMENT '使用者名稱',
`age` int(11) NOT NULL COMMENT '年齡',
`ctm` datetime NOT NULL COMMENT '建立時間',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('張三', '18', NOW()) ;
INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm` ) VALUES('李四', '20', NOW()) ;
INSERT INTO `db_test`.`tb_user` (`username`, `age`, `ctm`) VALUES('王五', '19', NOW()) ;
二、引入依賴
<!-- Spring-Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
另外web依賴也需要,因為我們採用MVC模式。
<!-- Add typical dependencies for a web application -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
三、資料庫配置檔案
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_user
username: root
password: root
四、程式碼
最開始使用mybati比較麻煩,各種配置檔案、實體類、dao層對映關聯、還有一大推其它配置。當然mybatis也發現了這種弊端,初期開發了generator可以根據表結果自動生產實體類、配置檔案和dao層程式碼,可以減輕一部分開發量;後期也進行了大量的優化可以使用註解了。
於是兩種使用方式都介紹一下,一、無配置註解版 二、配置檔案版
1.無配置檔案註解版
加入配置檔案
mybatis:
type-aliases-package: cn.saytime.bean
實體類User.class
package cn.saytime.bean;
import java.util.Date;
/**
* @ClassName cn.saytime.bean.User
* @Description
* @date 2017-07-04 22:47:28
*/
public class User {
private int id;
private String username;
private int age;
private Date ctm;
public User() {
}
public User(String username, int age) {
this.username = username;
this.age = age;
this.ctm = new Date();
}
// Getter、Setter
}
UserMapper.class
package cn.saytime.mapper;
import cn.saytime.bean.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
// @Mapper 這裡可以使用@Mapper註解,但是每個mapper都加註解比較麻煩,所以統一配置@MapperScan在掃描路徑在application類中
public interface UserMapper {
@Select("SELECT * FROM tb_user WHERE id = #{id}")
User getUserById(Integer id);
@Select("SELECT * FROM tb_user")
public List<User> getUserList();
@Insert("insert into tb_user(username, age, ctm) values(#{username}, #{age}, now())")
public int add(User user);
@Update("UPDATE tb_user SET username = #{user.username} , age = #{user.age} WHERE id = #{id}")
public int update(@Param("id") Integer id, @Param("user") User user);
@Delete("DELETE from tb_user where id = #{id} ")
public int delete(Integer id);
}
UserService.class
package cn.saytime.service;
import cn.saytime.bean.User;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName cn.saytime.service.UserService
* @Description
*/
public interface UserService {
User getUserById(Integer id);
public List<User> getUserList();
public int add(User user);
public int update(Integer id, User user);
public int delete(Integer id);
}
UserServiceimpl.class
package cn.saytime.service.impl;
import cn.saytime.bean.User;
import cn.saytime.mapper.UserMapper;
import cn.saytime.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName cn.saytime.service.impl.UserServiceImpl
* @Description
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}
@Override
public List<User> getUserList() {
return userMapper.getUserList();
}
@Override
public int add(User user) {
return userMapper.add(user);
}
@Override
public int update(Integer id, User user) {
return userMapper.update(id, user);
}
@Override
public int delete(Integer id) {
return userMapper.delete(id);
}
}
JsonResult.class 通用json返回類
package cn.saytime.bean;
public class JsonResult {
private String status = null;
private Object result = null;
public JsonResult status(String status) {
this.status = status;
return this;
}
// Getter Setter
}
UserController.class(Restful風格)
package cn.saytime.web;
import cn.saytime.bean.JsonResult;
import cn.saytime.bean.User;
import cn.saytime.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @ClassName cn.saytime.web.UserController
* @Description
* @date 2017-07-04 22:46:14
*/
@RestController
public class UserController {
@Autowired
private UserService userService;
/**
* 根據ID查詢使用者
* @param id
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
JsonResult r = new JsonResult();
try {
User user = userService.getUserById(id);
r.setResult(user);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 查詢使用者列表
* @return
*/
@RequestMapping(value = "users", method = RequestMethod.GET)
public ResponseEntity<JsonResult> getUserList (){
JsonResult r = new JsonResult();
try {
List<User> users = userService.getUserList();
r.setResult(users);
r.setStatus("ok");
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 新增使用者
* @param user
* @return
*/
@RequestMapping(value = "user", method = RequestMethod.POST)
public ResponseEntity<JsonResult> add (@RequestBody User user){
JsonResult r = new JsonResult();
try {
int orderId = userService.add(user);
if (orderId < 0) {
r.setResult(orderId);
r.setStatus("fail");
} else {
r.setResult(orderId);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 根據id刪除使用者
* @param id
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){
JsonResult r = new JsonResult();
try {
int ret = userService.delete(id);
if (ret < 0) {
r.setResult(ret);
r.setStatus("fail");
} else {
r.setResult(ret);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
/**
* 根據id修改使用者資訊
* @param user
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){
JsonResult r = new JsonResult();
try {
int ret = userService.update(id, user);
if (ret < 0) {
r.setResult(ret);
r.setStatus("fail");
} else {
r.setResult(ret);
r.setStatus("ok");
}
} catch (Exception e) {
r.setResult(e.getClass().getName() + ":" + e.getMessage());
r.setStatus("error");
e.printStackTrace();
}
return ResponseEntity.ok(r);
}
}
Application.java
package cn.saytime;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.saytime.mapper")
public class SpringbootMybaitsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybaitsApplication.class, args);
}
}
使用PostMan通過測試。
2.配置檔案版
加入配置檔案
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml
config-location: classpath:mybatis/mybatis-config.xml
專案目錄結構:
程式碼部分,相比於上面那種方式,改變的只有配置檔案以及下面幾個部分。
UserMapper.class
package cn.saytime.mapper;
import cn.saytime.bean.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @ClassName cn.saytime.mapper.UesrMapper
* @Description
*/
@Repository
public interface UserMapper {
User getUserById(Integer id);
public List<User> getUserList();
public int add(User user);
public int update(@Param("id") Integer id, @Param("user") User user);
public int delete(Integer id);
}
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
</typeAliases>
</configuration>
userMapper.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="cn.saytime.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="cn.saytime.bean.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="ctm" property="ctm" jdbcType="TIMESTAMP"/>
</resultMap>
<sql id="Base_Column_List" >
id, username, age, ctm
</sql>
<select id="getUserList" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM tb_user
</select>
<select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM tb_user
WHERE id = #{id}
</select>
<insert id="add" parameterType="cn.saytime.bean.User" >
INSERT INTO
tb_user
(username,age,ctm)
VALUES
(#{username}, #{age}, now())
</insert>
<update id="update" parameterType="java.util.Map" >
UPDATE
tb_user
SET
username = #{user.username},age = #{user.age}
WHERE
id = #{id}
</update>
<delete id="delete" parameterType="java.lang.Integer" >
DELETE FROM
tb_user
WHERE
id = #{id}
</delete>
</mapper>
上面這種方式也使用PostMan通過測試。
五、簡要說明
不知道大家有沒有注意到一點,就是引入Springboot-mybatis依賴的時候,並不是spring官方的starter,往常的springboot整合的依賴,比如web,redis等,groupId以及artifactId的地址如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
而這裡是mybatis為spring提供的starter依賴,所以依賴地址是:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
而且值得注意的是,這裡必須要指定版本號,往常我們使用springboot之所以不需要指定版本號,是因為我們引入的Maven Parent 中指定了SpringBoot的依賴,SpringBoot官方依賴Pom檔案中已經指定了它自己整合的第三方依賴的版本號,對於Mybatis,Spring官方並沒有提供自己的starter,所以必須跟正常的maven依賴一樣,要加版本號。