SpringBoot整合Mybatis实现增删改查的功能
Posted dzwyx521
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合Mybatis实现增删改查的功能相关的知识,希望对你有一定的参考价值。
SpringBoot框架作为现在主流框架之一,好多框架都渐渐的移植到SpringBoot中来。前面我给大家介绍过redis,jpa等等的的整合,今天在这里给大家介绍一下Mybatis的整合过程。
SpringBoot+Mybatis一般有两种形式。一种是采用原生的xml模式,还有一种就是采用注解模式。今天我给大家介绍的就是后者,也就是注解模式。
1.首选需要在SpringBoot的启动类里面增加用来扫描Mapper接口的注解,用来扫描Mapper包下面的接口。
- package com.joy;
- import org.mybatis.spring.annotation.MapperScan;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- @SpringBootApplication
- @MapperScan("com.joy.*")
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
在这里我扫描的是项目的根目录,只要能扫描到的包含Mapper接口的范围就可以。如果大家知道Mapper接口的具体位置,建议大家可以精确一点。
2.在application.properties配置文件中添加数据库的支持
- #DB Configuration:
- spring.datasource.driverClassName = com.mysql.jdbc.Driver
- spring.datasource.url = jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=utf-8&useSSL=false
- spring.datasource.username = root
- spring.datasource.password = 220316
这个关于数据库配置的代码其实很简单
第一个是数据库所用的驱动
第二个是数据库url地址,这里我连接的名字为mybatis_db数据库
第三第四是数据库连接的用户名和密码
3.pom.xml文件中添加相应的jar包
这里我就不一一介绍了,大家看一下demo就知道需要添加哪些内容了。
主要是SpringBoot相关的jar包,mybatis相关的jar包就ok了
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>springboot-mybatis</groupId>
- <artifactId>com.joy</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>com.joy Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.7.RELEASE</version>
- </parent>
- <properties>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- </dependency>
- <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
- <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
- <dependency>
- <groupId>com.github.pagehelper</groupId>
- <artifactId>pagehelper</artifactId>
- <version>4.1.0</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
- <build>
- <finalName>springboot-mybatis</finalName>
- </build>
- </project>
4.上面准备都完成了,我们就可以开始正式mybatis项目的开发了。这里需要先新建一个数据库映射的实体类,名字叫做UserEntity。
- package com.joy.entity;
- import java.util.Date;
- public class UserEntity {
- private long userId;
- private String userCode;
- private String userName;
- private String nickName;
- private String userPwd;
- private Date createDate;
- private Date updateDate;
- public long getUserId() {
- return userId;
- }
- public void setUserId(long userId) {
- this.userId = userId;
- }
- public String getUserCode() {
- return userCode;
- }
- public void setUserCode(String userCode) {
- this.userCode = userCode;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getNickName() {
- return nickName;
- }
- public void setNickName(String nickName) {
- this.nickName = nickName;
- }
- public String getUserPwd() {
- return userPwd;
- }
- public void setUserPwd(String userPwd) {
- this.userPwd = userPwd;
- }
- public Date getCreateDate() {
- return createDate;
- }
- public void setCreateDate(Date createDate) {
- this.createDate = createDate;
- }
- public Date getUpdateDate() {
- return updateDate;
- }
- public void setUpdateDate(Date updateDate) {
- this.updateDate = updateDate;
- }
- }
5.因为mybatis和jpa不一样,不会通过映射实体类反向生成数据库的表和字段。所以就得我们自己来新建一个表和字段。这里我新建一个user表。
我们可以利用navicat来手动的新建这张表并加相应的数据,也可以通过sql命令来实现,sql命令如下所示:
- SET FOREIGN_KEY_CHECKS=0;
- -- ----------------------------
- -- Table structure for user
- -- ----------------------------
- DROP TABLE IF EXISTS `user`;
- CREATE TABLE `user` (
- `user_id` int(10) NOT NULL AUTO_INCREMENT,
- `user_code` varchar(20) DEFAULT NULL,
- `user_name` varchar(20) DEFAULT NULL,
- `nick_name` varchar(20) DEFAULT NULL,
- `user_pwd` varchar(20) DEFAULT NULL,
- `create_date` datetime DEFAULT NULL,
- `update_date` datetime DEFAULT NULL,
- PRIMARY KEY (`user_id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
- -- ----------------------------
- -- Records of user
- -- ----------------------------
- INSERT INTO `user` VALUES (‘1‘, ‘10001‘, ‘user10001‘, ‘no1‘, ‘123456‘, ‘2017-10-22 15:23:32‘, ‘2017-10-22 15:23:35‘);
- 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的例子来给大家解释一下。- @Select("select * from user")
- @Results({
- @Result(property = "userId", column = "user_id"),
- @Result(property = "nickName", column = "nick_name"),
- @Result(property = "userCode", column = "user_code"),
- @Result(property = "userName", column = "user_name"),
- @Result(property = "userPwd", column = "user_pwd"),
- @Result(property = "createDate", column = "create_date"),
- @Result(property = "updateDate", column = "update_date") })
- public List<UserEntity> queryList();
- @Select("SELECT * FROM USER WHERE user_id = #{userId}")
- @Results({
- @Result(property = "userId", column = "user_id"),
- @Result(property = "nickName", column = "nick_name"),
- @Result(property = "userCode", column = "user_code"),
- @Result(property = "userName", column = "user_name"),
- @Result(property = "userPwd", column = "user_pwd"),
- @Result(property = "createDate", column = "create_date"),
- @Result(property = "updateDate", column = "update_date") })
- UserEntity findById(long userId);
下面将给出增删改查的所有代码,如下所示:
- package com.joy.dao;
- import java.util.List;
- import java.util.Map;
- import org.apache.ibatis.annotations.*;
- import com.joy.entity.UserEntity;
- public interface UserMapper {
- @Select("select * from user")
- @Results({
- @Result(property = "userId", column = "user_id"),
- @Result(property = "nickName", column = "nick_name"),
- @Result(property = "userCode", column = "user_code"),
- @Result(property = "userName", column = "user_name"),
- @Result(property = "userPwd", column = "user_pwd"),
- @Result(property = "createDate", column = "create_date"),
- @Result(property = "updateDate", column = "update_date") })
- public List<UserEntity> queryList();
- @Select("SELECT * FROM USER WHERE user_id = #{userId}")
- @Results({
- @Result(property = "userId", column = "user_id"),
- @Result(property = "nickName", column = "nick_name"),
- @Result(property = "userCode", column = "user_code"),
- @Result(property = "userName", column = "user_name"),
- @Result(property = "userPwd", column = "user_pwd"),
- @Result(property = "createDate", column = "create_date"),
- @Result(property = "updateDate", column = "update_date") })
- UserEntity findById(long userId);
- @Insert("INSERT INTO USER(nick_name, user_code) VALUES(#{nickName}, #{userCode})")
- int insertParam(@Param("nickName") String nickName, @Param("userCode") String userCode);
- @Insert("INSERT INTO USER(nick_name, user_code) VALUES(#{nickName,jdbcType=VARCHAR}, #{userCode,jdbcType=INTEGER})")
- int insertByMap(Map<String, Object> map);
- @Insert("insert into user(nick_name,user_code,user_name,user_pwd,create_date,update_date) values(#{nickName},#{userCode},#{userName},#{userPwd},#{createDate},#{updateDate})")
- public int insertEntity(UserEntity entity);
- @Update("UPDATE user SET nick_name=#{nickName} WHERE user_id=#{userId}")
- int updateEntity(UserEntity user);
- @Delete("DELETE FROM user WHERE user_id =#{userId}")
- int delete(Long userId);
- @Delete("DELETE FROM user WHERE user_id =#{userId}")
- int deleteEntity(UserEntity entity);
- }
7.最后就是编写相应的service和controller类来调用这些增删改查的接口。
service类信息:- package com.joy.service;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import com.joy.dao.UserMapper;
- import com.joy.entity.UserEntity;
- @Service
- public class UserService {
- @Autowired(required = false)
- private UserMapper mapper;
- public List<UserEntity> queryList(){
- List<UserEntity> userList=mapper.queryList();
- return userList;
- }
- public UserEntity findById(long userId){
- System.out.println("userId:"+userId);
- return mapper.findById(userId);
- }
- public int insertEntity() {
- UserEntity entity=new UserEntity();
- entity.setUserName("lisi");
- entity.setUserCode("lisi"+new Date());
- entity.setNickName("郭靖");
- entity.setUserPwd("123");
- entity.setCreateDate(new Date());
- entity.setUpdateDate(new Date());
- return mapper.insertEntity(entity);
- }
- public int insertParam() {
- return mapper.insertParam("linzhiqiang","lzq");
- }
- public int insertByMap() {
- Map<String, Object> map=new HashMap<String, Object>();
- map.put("nickName","zhaotong");
- map.put("userCode","zt");
- return mapper.insertByMap(map);
- }
- public int updateEntity() {
- UserEntity entity=new UserEntity();
- entity.setUserId(1);
- entity.setNickName("郭靖");
- return mapper.updateEntity(entity);
- }
- public int deleteEntity() {
- UserEntity entity=new UserEntity();
- entity.setUserId(11);
- return mapper.deleteEntity(entity);
- }
- }
- package com.joy.controller;
- import java.util.List;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- import com.github.pagehelper.PageHelper;
- import com.joy.entity.UserEntity;
- import com.joy.service.UserService;
- @RestController
- public class UserController {
- @Autowired
- private UserService userService;
- @RequestMapping("/userlist")
- public List<UserEntity> queryList(){
- PageHelper.startPage(1, 2);
- return userService.queryList();
- }
- @RequestMapping("/queryUser")
- public UserEntity queryUserEntity(long userId){
- UserEntity userEntity=userService.findById(userId);
- return userEntity;
- }
- @RequestMapping("/insert")
- public int insertEntity() {
- return userService.insertEntity();
- }
- @RequestMapping("/insertParam")
- public int insertParam() {
- return userService.insertParam();
- }
- @RequestMapping("/insertByMap")
- public int insertByMap() {
- return userService.insertByMap();
- }
- @RequestMapping("/updateEntity")
- public int updateEntity() {
- return userService.updateEntity();
- }
- @RequestMapping("/deleteEntity")
- public int deleteEntity() {
- return userService.deleteEntity();
- }
- }
8.如果想要将执行的sql打印在控制台上面,可以在application.properties添加如下的配置信息。
logging.level.com.joy=DEBUG
这里需要特别注意的是:level后面是你项目包的地址不要写的和我一样。到这里关于SpringBoot整合Mybatis项目就介绍完毕,如果大家想要源代码的话可以去我的GitHub地址下载。
如果按照博客上面写的步骤操作还有问题,可以观看我为大家录制的视频讲解。因为本人不是专业的讲师,所以可能讲的不是特别细致。有什么建议都可以提出来,谢谢大家。视频地址:https://pan.baidu.com/s/1qYcFDow点击打开链接
如果大家对文章有什么问题或者疑意之类的,可以加我订阅号在上面留言,订阅号上面我会定期更新最新博客。如果嫌麻烦可以直接加我wechat:lzqcode
以上是关于SpringBoot整合Mybatis实现增删改查的功能的主要内容,如果未能解决你的问题,请参考以下文章
ShardingSpherespringboot整合shardingjdbc+mybatis进行增删改查