SpringBoot整合Mybatis實現增刪改查的功能


SpringBoot框架作為現在主流框架之一,好多框架都漸漸的移植到SpringBoot中來。前面我給大家介紹過redis,jpa等等的的整合,今天在這里給大家介紹一下Mybatis的整合過程。

 

SpringBoot+Mybatis一般有兩種形式。一種是采用原生的xml模式,還有一種就是采用注解模式。今天我給大家介紹的就是后者,也就是注解模式。
1.首選需要在SpringBoot的啟動類里面增加用來掃描Mapper接口的注解,用來掃描Mapper包下面的接口。
[java] view plain copy
 
  1. package com.joy;  
  2. import org.mybatis.spring.annotation.MapperScan;  
  3. import org.springframework.boot.SpringApplication;  
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  5. @SpringBootApplication  
  6. @MapperScan("com.joy.*")  
  7. public class App {  
  8.     public static void main(String[] args) {  
  9.         SpringApplication.run(App.class, args);  
  10.     }  
  11. }  
在這里我掃描的是項目的根目錄,只要能掃描到的包含Mapper接口的范圍就可以。如果大家知道Mapper接口的具體位置,建議大家可以精確一點。
2.在application.properties配置文件中添加數據庫的支持
[html] view plain copy
 
  1. #DB Configuration:  
  2. spring.datasource.driverClassName = com.mysql.jdbc.Driver  
  3. spring.datasource.url = jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=utf-8&useSSL=false  
  4. spring.datasource.username = root  
  5. spring.datasource.password = 220316  
這個關於數據庫配置的代碼其實很簡單
第一個是數據庫所用的驅動
第二個是數據庫url地址,這里我連接的名字為mybatis_db數據庫
第三第四是數據庫連接的用戶名和密碼
3.pom.xml文件中添加相應的jar包
這里我就不一一介紹了,大家看一下demo就知道需要添加哪些內容了。
主要是SpringBoot相關的jar包,mybatis相關的jar包就ok了
[html] view plain copy
 
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>springboot-mybatis</groupId>  
  5.     <artifactId>com.joy</artifactId>  
  6.     <packaging>war</packaging>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <name>com.joy Maven Webapp</name>  
  9.     <url>http://maven.apache.org</url>  
  10.     <parent>  
  11.         <groupId>org.springframework.boot</groupId>  
  12.         <artifactId>spring-boot-starter-parent</artifactId>  
  13.         <version>1.5.7.RELEASE</version>  
  14.     </parent>  
  15.     <properties>  
  16.         <java.version>1.8</java.version>  
  17.     </properties>  
  18.     <dependencies>  
  19.         <dependency>  
  20.             <groupId>org.springframework.boot</groupId>  
  21.             <artifactId>spring-boot-starter-web</artifactId>  
  22.         </dependency>  
  23.         <dependency>  
  24.             <groupId>javax.servlet</groupId>  
  25.             <artifactId>javax.servlet-api</artifactId>  
  26.         </dependency>  
  27.         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->  
  28.         <dependency>  
  29.             <groupId>mysql</groupId>  
  30.             <artifactId>mysql-connector-java</artifactId>  
  31.         </dependency>  
  32.         <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->  
  33.         <dependency>  
  34.             <groupId>com.github.pagehelper</groupId>  
  35.             <artifactId>pagehelper</artifactId>  
  36.             <version>4.1.0</version>  
  37.         </dependency>  
  38.         <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->  
  39.         <dependency>  
  40.             <groupId>org.mybatis.spring.boot</groupId>  
  41.             <artifactId>mybatis-spring-boot-starter</artifactId>  
  42.             <version>1.2.2</version>  
  43.         </dependency>  
  44.   
  45.         <dependency>  
  46.             <groupId>junit</groupId>  
  47.             <artifactId>junit</artifactId>  
  48.             <scope>test</scope>  
  49.         </dependency>  
  50.     </dependencies>  
  51.     <build>  
  52.         <finalName>springboot-mybatis</finalName>  
  53.     </build>  
  54. </project>  
4.上面准備都完成了,我們就可以開始正式mybatis項目的開發了。這里需要先新建一個數據庫映射的實體類,名字叫做UserEntity。
[java] view plain copy
 
  1. package com.joy.entity;  
  2. import java.util.Date;  
  3. public class UserEntity {  
  4.     private long userId;  
  5.     private String userCode;  
  6.     private String userName;  
  7.     private String nickName;  
  8.     private String userPwd;  
  9.     private Date createDate;  
  10.     private Date updateDate;  
  11.     public long getUserId() {  
  12.         return userId;  
  13.     }  
  14.     public void setUserId(long userId) {  
  15.         this.userId = userId;  
  16.     }  
  17.     public String getUserCode() {  
  18.         return userCode;  
  19.     }  
  20.     public void setUserCode(String userCode) {  
  21.         this.userCode = userCode;  
  22.     }  
  23.     public String getUserName() {  
  24.         return userName;  
  25.     }  
  26.     public void setUserName(String userName) {  
  27.         this.userName = userName;  
  28.     }  
  29.     public String getNickName() {  
  30.         return nickName;  
  31.     }  
  32.     public void setNickName(String nickName) {  
  33.         this.nickName = nickName;  
  34.     }  
  35.     public String getUserPwd() {  
  36.         return userPwd;  
  37.     }  
  38.     public void setUserPwd(String userPwd) {  
  39.         this.userPwd = userPwd;  
  40.     }  
  41.     public Date getCreateDate() {  
  42.         return createDate;  
  43.     }  
  44.     public void setCreateDate(Date createDate) {  
  45.         this.createDate = createDate;  
  46.     }  
  47.     public Date getUpdateDate() {  
  48.         return updateDate;  
  49.     }  
  50.     public void setUpdateDate(Date updateDate) {  
  51.         this.updateDate = updateDate;  
  52.     }  
  53. }  
5.因為mybatis和jpa不一樣,不會通過映射實體類反向生成數據庫的表和字段。所以就得我們自己來新建一個表和字段。這里我新建一個user表。

我們可以利用navicat來手動的新建這張表並加相應的數據,也可以通過sql命令來實現,sql命令如下所示:
[sql] view plain copy
 
  1. SET FOREIGN_KEY_CHECKS=0;  
  2. -- ----------------------------  
  3. -- Table structure for user  
  4. -- ----------------------------  
  5. DROP TABLE IF EXISTS `user`;  
  6. CREATE TABLE `user` (  
  7.   `user_id` int(10) NOT NULL AUTO_INCREMENT,  
  8.   `user_code` varchar(20) DEFAULT NULL,  
  9.   `user_name` varchar(20) DEFAULT NULL,  
  10.   `nick_name` varchar(20) DEFAULT NULL,  
  11.   `user_pwd` varchar(20) DEFAULT NULL,  
  12.   `create_date` datetime DEFAULT NULL,  
  13.   `update_date` datetime DEFAULT NULL,  
  14.   PRIMARY KEY (`user_id`)  
  15. ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;  
  16. -- ----------------------------  
  17. -- Records of user  
  18. -- ----------------------------  
  19. INSERT INTO `user` VALUES ('1', '10001', 'user10001', 'no1', '123456', '2017-10-22 15:23:32', '2017-10-22 15:23:35');  
  20. INSERT INTO `user` VALUES ('2', '10002', 'user10002', 'no2', '123456', '2017-10-22 15:23:32', '2017-10-22 15:23:35');  
6.接下來就是最重要的編寫Mapper接口,我們這里采用通過注解來實現數據庫的增刪改查功能。
增刪改查分別對應的注解為@Insert,@Delete,@Update,@Select
關於注解的使用細節,我這里舉select的例子來給大家解釋一下。
[java] view plain copy
 
  1. @Select("select * from user")  
  2.     @Results({  
  3.             @Result(property = "userId", column = "user_id"),  
  4.             @Result(property = "nickName", column = "nick_name"),  
  5.             @Result(property = "userCode", column = "user_code"),   
  6.             @Result(property = "userName", column = "user_name"),  
  7.             @Result(property = "userPwd", column = "user_pwd"),  
  8.             @Result(property = "createDate", column = "create_date"),  
  9.             @Result(property = "updateDate", column = "update_date") })  
  10.     public List<UserEntity> queryList();  
上面是查詢數據庫user表的所有數據,然后會自動的轉為list集合。其中column里面的字段名稱必須和數據庫里面表的字段一模一樣,property里面的字段屬性必須和UserEntity這個實體類對應的字段一模一樣。
[java] view plain copy
 
  1. @Select("SELECT * FROM USER WHERE user_id = #{userId}")  
  2.     @Results({  
  3.             @Result(property = "userId", column = "user_id"),  
  4.             @Result(property = "nickName", column = "nick_name"),  
  5.             @Result(property = "userCode", column = "user_code"),  
  6.             @Result(property = "userName", column = "user_name"),  
  7.             @Result(property = "userPwd", column = "user_pwd"),  
  8.             @Result(property = "createDate", column = "create_date"),  
  9.             @Result(property = "updateDate", column = "update_date") })  
  10.     UserEntity findById(long userId);  
上面這種形式是通過傳入一個字段來查詢數據。這里需要注意的是#{}里面的字段內容必須和findById里面傳入的字段一模一樣。除了#{}以外的字段都必須滿足sql的查詢格式。這里大家不要誤解了,findById可以隨便定義和jpa中是不一樣的。
下面將給出增刪改查的所有代碼,如下所示:
[java] view plain copy
 
  1. package com.joy.dao;  
  2. import java.util.List;  
  3. import java.util.Map;  
  4. import org.apache.ibatis.annotations.*;  
  5. import com.joy.entity.UserEntity;  
  6. public interface UserMapper {  
  7.     @Select("select * from user")  
  8.     @Results({  
  9.             @Result(property = "userId", column = "user_id"),  
  10.             @Result(property = "nickName", column = "nick_name"),  
  11.             @Result(property = "userCode", column = "user_code"),   
  12.             @Result(property = "userName", column = "user_name"),  
  13.             @Result(property = "userPwd", column = "user_pwd"),  
  14.             @Result(property = "createDate", column = "create_date"),  
  15.             @Result(property = "updateDate", column = "update_date") })  
  16.     public List<UserEntity> queryList();  
  17.     @Select("SELECT * FROM USER WHERE user_id = #{userId}")  
  18.     @Results({  
  19.             @Result(property = "userId", column = "user_id"),  
  20.             @Result(property = "nickName", column = "nick_name"),  
  21.             @Result(property = "userCode", column = "user_code"),  
  22.             @Result(property = "userName", column = "user_name"),  
  23.             @Result(property = "userPwd", column = "user_pwd"),  
  24.             @Result(property = "createDate", column = "create_date"),  
  25.             @Result(property = "updateDate", column = "update_date") })  
  26.     UserEntity findById(long userId);  
  27.   
  28.     @Insert("INSERT INTO USER(nick_name, user_code) VALUES(#{nickName}, #{userCode})")  
  29.     int insertParam(@Param("nickName") String nickName, @Param("userCode") String userCode);  
  30.   
  31.     @Insert("INSERT INTO USER(nick_name, user_code) VALUES(#{nickName,jdbcType=VARCHAR}, #{userCode,jdbcType=INTEGER})")  
  32.     int insertByMap(Map<String, Object> map);  
  33.   
  34.     @Insert("insert into user(nick_name,user_code,user_name,user_pwd,create_date,update_date) values(#{nickName},#{userCode},#{userName},#{userPwd},#{createDate},#{updateDate})")  
  35.     public int insertEntity(UserEntity entity);  
  36.   
  37.     @Update("UPDATE user SET nick_name=#{nickName} WHERE user_id=#{userId}")  
  38.     int updateEntity(UserEntity user);  
  39.   
  40.     @Delete("DELETE FROM user WHERE user_id =#{userId}")  
  41.     int delete(Long userId);  
  42.   
  43.     @Delete("DELETE FROM user WHERE user_id =#{userId}")  
  44.     int deleteEntity(UserEntity entity);  
  45. }  
7.最后就是編寫相應的service和controller類來調用這些增刪改查的接口。
service類信息:
[java] view plain copy
 
  1. package com.joy.service;  
  2. import java.util.Date;  
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Service;  
  8. import com.joy.dao.UserMapper;  
  9. import com.joy.entity.UserEntity;  
  10. @Service  
  11. public class UserService {  
  12.     @Autowired(required = false)  
  13.     private UserMapper mapper;  
  14.       
  15.     public List<UserEntity> queryList(){  
  16.         List<UserEntity> userList=mapper.queryList();  
  17.         return userList;  
  18.     }  
  19.   
  20.     public UserEntity findById(long userId){  
  21.         System.out.println("userId:"+userId);  
  22.         return mapper.findById(userId);  
  23.     }  
  24.   
  25.     public int insertEntity() {  
  26.         UserEntity entity=new UserEntity();  
  27.         entity.setUserName("lisi");  
  28.         entity.setUserCode("lisi"+new Date());  
  29.         entity.setNickName("郭靖");  
  30.         entity.setUserPwd("123");  
  31.         entity.setCreateDate(new Date());  
  32.         entity.setUpdateDate(new Date());  
  33.         return mapper.insertEntity(entity);  
  34.     }  
  35.   
  36.     public int insertParam() {  
  37.         return mapper.insertParam("linzhiqiang","lzq");  
  38.     }  
  39.   
  40.     public int insertByMap() {  
  41.         Map<String, Object> map=new HashMap<String, Object>();  
  42.         map.put("nickName","zhaotong");  
  43.         map.put("userCode","zt");  
  44.         return mapper.insertByMap(map);  
  45.     }  
  46.   
  47.     public int updateEntity() {  
  48.         UserEntity entity=new UserEntity();  
  49.         entity.setUserId(1);  
  50.         entity.setNickName("郭靖");  
  51.         return mapper.updateEntity(entity);  
  52.     }  
  53.   
  54.     public int deleteEntity() {  
  55.         UserEntity entity=new UserEntity();  
  56.         entity.setUserId(11);  
  57.         return mapper.deleteEntity(entity);  
  58.     }  
  59. }  
controller類信息:
[java] view plain copy
 
  1. package com.joy.controller;  
  2. import java.util.List;  
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.web.bind.annotation.RequestMapping;  
  5. import org.springframework.web.bind.annotation.RestController;  
  6. import com.github.pagehelper.PageHelper;  
  7. import com.joy.entity.UserEntity;  
  8. import com.joy.service.UserService;  
  9. @RestController  
  10. public class UserController {  
  11.     @Autowired  
  12.     private UserService userService;  
  13.     @RequestMapping("/userlist")  
  14.     public List<UserEntity> queryList(){  
  15.         PageHelper.startPage(1, 2);  
  16.         return userService.queryList();  
  17.     }  
  18.   
  19.     @RequestMapping("/queryUser")  
  20.     public UserEntity queryUserEntity(long userId){  
  21.         UserEntity userEntity=userService.findById(userId);  
  22.         return userEntity;  
  23.     }  
  24.   
  25.     @RequestMapping("/insert")  
  26.     public int insertEntity() {  
  27.         return userService.insertEntity();  
  28.     }  
  29.   
  30.     @RequestMapping("/insertParam")  
  31.     public int insertParam() {  
  32.         return userService.insertParam();  
  33.     }  
  34.   
  35.     @RequestMapping("/insertByMap")  
  36.     public int insertByMap() {  
  37.         return userService.insertByMap();  
  38.     }  
  39.   
  40.     @RequestMapping("/updateEntity")  
  41.     public int updateEntity() {  
  42.         return userService.updateEntity();  
  43.     }  
  44.   
  45.     @RequestMapping("/deleteEntity")  
  46.     public int deleteEntity() {  
  47.         return userService.deleteEntity();  
  48.     }  
  49. }  
8.執行結果如下所示:
8.如果想要將執行的sql打印在控制台上面,可以在application.properties添加如下的配置信息。
logging.level.com.joy=DEBUG
這里需要特別注意的是:level后面是你項目包的地址不要寫的和我一樣。
到這里關於SpringBoot整合Mybatis項目就介紹完畢,如果大家想要源代碼的話可以去我的GitHub地址下載。
如果按照博客上面寫的步驟操作還有問題,可以觀看我為大家錄制的視頻講解。因為本人不是專業的講師,所以可能講的不是特別細致。有什么建議都可以提出來,謝謝大家。視頻地址:https://pan.baidu.com/s/1qYcFDow 點擊打開鏈接
如果大家對文章有什么問題或者疑意之類的,可以加我訂閱號在上面留言,訂閱號上面我會定期更新最新博客。如果嫌麻煩可以直接加我wechat:lzqcode


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM