1. 程式人生 > >SpringBoot整合Mybatis實現增刪改查的功能

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

ger 開始 pan ble img 映射 講師 -name date

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. <dependency>
  45. <groupId>junit</groupId>
  46. <artifactId>junit</artifactId>
  47. <scope>test</scope>
  48. </dependency>
  49. </dependencies>
  50. <build>
  51. <finalName>springboot-mybatis</finalName>
  52. </build>
  53. </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. @Insert("INSERT INTO USER(nick_name, user_code) VALUES(#{nickName}, #{userCode})")
  28. int insertParam(@Param("nickName") String nickName, @Param("userCode") String userCode);
  29. @Insert("INSERT INTO USER(nick_name, user_code) VALUES(#{nickName,jdbcType=VARCHAR}, #{userCode,jdbcType=INTEGER})")
  30. int insertByMap(Map<String, Object> map);
  31. @Insert("insert into user(nick_name,user_code,user_name,user_pwd,create_date,update_date) values(#{nickName},#{userCode},#{userName},#{userPwd},#{createDate},#{updateDate})")
  32. public int insertEntity(UserEntity entity);
  33. @Update("UPDATE user SET nick_name=#{nickName} WHERE user_id=#{userId}")
  34. int updateEntity(UserEntity user);
  35. @Delete("DELETE FROM user WHERE user_id =#{userId}")
  36. int delete(Long userId);
  37. @Delete("DELETE FROM user WHERE user_id =#{userId}")
  38. int deleteEntity(UserEntity entity);
  39. }
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. public List<UserEntity> queryList(){
  15. List<UserEntity> userList=mapper.queryList();
  16. return userList;
  17. }
  18. public UserEntity findById(long userId){
  19. System.out.println("userId:"+userId);
  20. return mapper.findById(userId);
  21. }
  22. public int insertEntity() {
  23. UserEntity entity=new UserEntity();
  24. entity.setUserName("lisi");
  25. entity.setUserCode("lisi"+new Date());
  26. entity.setNickName("郭靖");
  27. entity.setUserPwd("123");
  28. entity.setCreateDate(new Date());
  29. entity.setUpdateDate(new Date());
  30. return mapper.insertEntity(entity);
  31. }
  32. public int insertParam() {
  33. return mapper.insertParam("linzhiqiang","lzq");
  34. }
  35. public int insertByMap() {
  36. Map<String, Object> map=new HashMap<String, Object>();
  37. map.put("nickName","zhaotong");
  38. map.put("userCode","zt");
  39. return mapper.insertByMap(map);
  40. }
  41. public int updateEntity() {
  42. UserEntity entity=new UserEntity();
  43. entity.setUserId(1);
  44. entity.setNickName("郭靖");
  45. return mapper.updateEntity(entity);
  46. }
  47. public int deleteEntity() {
  48. UserEntity entity=new UserEntity();
  49. entity.setUserId(11);
  50. return mapper.deleteEntity(entity);
  51. }
  52. }
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. @RequestMapping("/queryUser")
  19. public UserEntity queryUserEntity(long userId){
  20. UserEntity userEntity=userService.findById(userId);
  21. return userEntity;
  22. }
  23. @RequestMapping("/insert")
  24. public int insertEntity() {
  25. return userService.insertEntity();
  26. }
  27. @RequestMapping("/insertParam")
  28. public int insertParam() {
  29. return userService.insertParam();
  30. }
  31. @RequestMapping("/insertByMap")
  32. public int insertByMap() {
  33. return userService.insertByMap();
  34. }
  35. @RequestMapping("/updateEntity")
  36. public int updateEntity() {
  37. return userService.updateEntity();
  38. }
  39. @RequestMapping("/deleteEntity")
  40. public int deleteEntity() {
  41. return userService.deleteEntity();
  42. }
  43. }
8.執行結果如下所示:
技術分享圖片技術分享圖片 8.如果想要將執行的sql打印在控制臺上面,可以在application.properties添加如下的配置信息。 logging.level.com.joy=DEBUG 這裏需要特別註意的是:level後面是你項目包的地址不要寫的和我一樣。 到這裏關於SpringBoot整合Mybatis項目就介紹完畢,如果大家想要源代碼的話可以去我的GitHub地址下載。
GitHub地址:https://github.com/1913045515/MyBatis.git 如果按照博客上面寫的步驟操作還有問題,可以觀看我為大家錄制的視頻講解。因為本人不是專業的講師,所以可能講的不是特別細致。有什麽建議都可以提出來,謝謝大家。視頻地址:https://pan.baidu.com/s/1qYcFDow點擊打開鏈接 如果大家對文章有什麽問題或者疑意之類的,可以加我訂閱號在上面留言,訂閱號上面我會定期更新最新博客。如果嫌麻煩可以直接加我wechat:lzqcode 技術分享圖片

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