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();

上面是查询数据库user表的所有数据,然后会自动的转为list集合。其中column里面的字段名称必须和数据库里面表的字段一模一样,property里面的字段属性必须和UserEntity这个实体类对应的字段一模一样。

@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);

上面这种形式是通过传入一个字段来查询数据。这里需要注意的是#{}里面的字段内容必须和findById里面传入的字段一模一样。除了#{}以外的字段都必须满足sql的查询格式。这里大家不要误解了,findById可以随便定义和jpa中是不一样的。

下面将给出增删改查的所有代码,如下所示:

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);
    }
}

controller类信息:

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.执行结果如下所示:

8.如果想要将执行的sql打印在控制台上面,可以在application.properties添加如下的配置信息。

logging.level.com.joy=DEBUG

这里需要特别注意的是:level后面是你项目包的地址不要写的和我一样。

到这里关于SpringBoot整合Mybatis项目就介绍完毕,如果大家想要源代码的话可以去我的GitHub地址下载。

GitHub地址:https://github.com/1913045515/MyBatis.git

如果对上面的内容还有什么疑义或者问题都可以加我QQ:208017534或者微信:qiang220316咨询

如果按照文章上面写的步骤操作还有问题,可以观看我为大家录制的视频讲解。因为本人不是专业的讲师,所以可能讲的不是特别细致。有什么建议都可以提出来,谢谢大家。

视频地址:点击打开链接

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Spark学习技巧

Spark 下操作 HBase(1.0.0 新 API)

hbase1.0.0版本提供了一些让人激动的功能,并且,在不牺牲稳定性的前提下,引入了新的API。虽然 1.0.0 兼容旧版本的 API,不过还是应该尽早地来熟...

732
来自专栏小樱的经验随笔

2017 Multi-University Training Contest - Team 1 1011&&HDU 6043 KazaQ's Socks【规律题,数学,水】

KazaQ's Socks Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131...

2605
来自专栏后台及大数据开发

Linux巩固记录(4) 运行hadoop 2.7.4自带demo程序验证环境

391
来自专栏计算机视觉与深度学习基础

Leetcode 235. Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two ...

1919
来自专栏菩提树下的杨过

基于sliverlight + wcf的web 文字版IM 示例

演示地址: http://task.24city.com/default.html 预览界面: ? 一、布局 采用Grid布局,5行2列 第一行:为登录/注册信...

3136
来自专栏一个会写诗的程序员的博客

Kotlin Compiler Plugins : All-open , Kotlin-spring,No-arg,Kotlin-jpaCompiler Plugins

Kotlin has classes and their members final by default, which makes it inconvenie...

742
来自专栏c#开发者

How to crop scanned barcode using Zbar?

http://pastebin.com/wSVW1tRc CGRect scanCrop The region of the video image tha...

3027
来自专栏包子铺里聊IT

劳动最光荣!Double Letter Problem from TopCoder

包子IT面试培训 助你拿到理想的offer! 这是TopCoder上面一道比较简单的250分的题目,非常适合作为面试的第一道热身题目,考察了面试者对于基本的数据...

2606
来自专栏everhad

Android AppBar

AppBar官方文档摘记 2016-6-12 本文摘自Android官方文档,为方便自己及其他开发者朋友阅读。 章节目录为“Develop > Trainin...

1996
来自专栏Kubernetes

kube-scheduler最佳配置

version: kubernetes 1.6.2 ##kube-scheduler Configuration 下面是我梳理的kube-scheduler的完...

2758

扫码关注云+社区