前言:
首先我们在使用java开发应用时访问数据库是必不可少的。当然行业内都会使用相关的开源框架提高开发效率。这里我们使用springboot+MyBatis-Plus进行讲解。为新手朋友们大致描述一下如何使用并且集成。
这篇文章我们是基于xml配置sql语句的方式访问数据库,简单来讲就是你的sql语句需要写在项目点一个xml中。当然MyBatis-Plus还有很多高级的编写sql语句的方式。我们这里使用一个比较常见的一种。
这里我们使用的springboot 版本是2.4.5,mybatis-plus版本我们使用的是3.4.2。我的数据库使用的是mysql 8.0.23
阅读mybatisplus官方文档了解到 https://mp.baomidou.com/guide/
如果你的项目是使用的springboot框架那你的maven依赖请使用如下(版本自己选择)
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
如果你的项目是使用的普通的spring框架,比如一个原始的tomcat应用,并没有涉及到springboot范畴 那你的maven依赖请使用如下(版本自己选择)
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.4.2</version>
</dependency>
由于一些刚刚入行的朋友在网络上查询一些资料,资料也没有清楚maven依赖的组合,很容易让您混乱使用,导致代码不规范,或者依赖冲突等等
1:数据库表结构
CREATE TABLE `web_user` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_name` varchar(20) NOT NULL COMMENT '用户名',
`password` varchar(64) NOT NULL COMMENT '密码',
`user_email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`user_age` int DEFAULT NULL,
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `web_user` VALUES (1, 'test_123', 'psd123', 'psd@136.com', 45, '2021-05-02 17:40:00', '2021-05-02 17:40:05');
2:创建springboot项目同时引入mybatis-plus 全依赖
如下 是我们maven依赖细节!
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.shidifen.mybatisplus</groupId>
<artifactId>mybatis-plus-breakthrough</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis-plus-breakthrough</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2:代码目录结构
3:代码细节
3.1关于application.yml内容
server:
port: 8888 #tomcat端口
spring:
application:
name: mybatis-plus-breakthrough-server
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver #数据库驱动
url: jdbc:mysql://localhost:3306/test_mybatis_plus?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=GMT%2b8&useSSL=false #数据库连接信息
username: root
password: 123
mybatis-plus:
type-aliases-package: com.shidifen.mybatis.plus.breakthrough.pojo.entity #这个配置的目的是告诉mybatis-Plus 数据库表与java实体对应的包位置,
mapper-locations: classpath:mapper/*Mapper.xml #这个是告诉mybatis-Plus 扫描 Mapper.xml的位置
check-config-location: true #是否执行MyBatis xml配置文件的状态检查, 只是检查状态
3.2关于main函数
package com.shidifen.mybatis.plus.breakthrough;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author 史蒂芬暴风
*/
@SpringBootApplication
@MapperScan("com.shidifen.mybatis.plus.breakthrough.dao")//主要是这段代码,我们需要让spring扫描dao包
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3.3关于 WebUser.java和 WebUserVo.java
package com.shidifen.mybatis.plus.breakthrough.pojo.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.Date;
/**
* @author shidifen
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("web_User") //这个注解写入您数据库表的名称,这个java实体就对应你数据库里的表
public class WebUser extends Model<WebUser> {
@Override
protected Serializable pkVal() {
return this.id;
}
/**
* 主键id
*/
@TableId(value = "id", type = IdType.AUTO) //主键
private Long id;
@TableField("user_name") //@TableField 这个注解主要是描述java字段对应表的字段
private String userName;
@TableField("password")
private String password;
@TableField("user_email")
private String userEmail;
@TableField("user_age")
private String userAge;
@TableField("create_time")
private Date createTime;
@TableField("create_time")
private Date updateTime;
}
package com.shidifen.mybatis.plus.breakthrough.pojo.vo;
import com.shidifen.mybatis.plus.breakthrough.pojo.entity.WebUser;
/**
* @author shidifen
*/
public class WebUserVo extends WebUser {
}
3.4 WebUserDao文件(DataAccessobjects 数据存取对象)
package com.shidifen.mybatis.plus.breakthrough.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.shidifen.mybatis.plus.breakthrough.pojo.entity.WebUser;
/**
* @author shidifen
*/
public interface WebUserDao extends BaseMapper<WebUser> {
/**
* 通过用户名查找用户信息
* @param userName
* @return
*/
WebUser selectByUserName(String userName);
}
3.5 WebUserService文件和 WebUserServiceImpl文件
package com.shidifen.mybatis.plus.breakthrough.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.shidifen.mybatis.plus.breakthrough.pojo.entity.WebUser;
import com.shidifen.mybatis.plus.breakthrough.pojo.vo.WebUserVo;
/**
* @author shidifen
*/
public interface WebUserService extends IService<WebUser> {
/**
* 登录
* @param webUserVo
* @return
*/
boolean login(WebUserVo webUserVo);
}
package com.shidifen.mybatis.plus.breakthrough.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shidifen.mybatis.plus.breakthrough.dao.WebUserDao;
import com.shidifen.mybatis.plus.breakthrough.pojo.entity.WebUser;
import com.shidifen.mybatis.plus.breakthrough.pojo.vo.WebUserVo;
import com.shidifen.mybatis.plus.breakthrough.service.WebUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Objects;
/**
* @author shidifen
*/
@Service
public class WebUserServiceImpl extends ServiceImpl<WebUserDao, WebUser> implements WebUserService {
@Autowired
private WebUserDao webUserDao;
@Override
public boolean login(WebUserVo webUserVo) {
WebUser webUser = webUserDao.selectByUserName(webUserVo.getUserName());
if (Objects.nonNull(webUser) && webUser.getPassword().equals(webUserVo.getPassword())) {
return true;
}
return false;
}
}
3.6 WebUserController 文件
package com.shidifen.mybatis.plus.breakthrough.controller;
import com.shidifen.mybatis.plus.breakthrough.pojo.vo.WebUserVo;
import com.shidifen.mybatis.plus.breakthrough.service.WebUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author shidifen
*/
@RestController
@RequestMapping("/web_user")
@Slf4j
public class WebUserController {
@Autowired
private WebUserService webUserService;
@PostMapping("/login")
public boolean login(@RequestBody WebUserVo webUserVo) {
return webUserService.login(webUserVo);
}
}
3.7 WebUserMapper.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="com.shidifen.mybatis.plus.breakthrough.dao.WebUserDao">
<!-- 通用查询映射结果 -->
<resultMap id="webUserResultMap" type="com.shidifen.mybatis.plus.breakthrough.pojo.entity.WebUser">
<id column="id" property="id" />
<result column="user_name" property="userName" />
<result column="password" property="password" />
<result column="user_email" property="userEmail" />
<result column="create_time" property="createTime" />
<result column="update_time" property="updateTime" />
<result column="user_age" property="userAge"/>
</resultMap>
<!-- 通用查询结果列 -->
<sql id="baseColumnList">
imei, car_num, operator, corporation_Id, create_time, update_time
</sql>
<select id="selectByUserName" resultMap="webUserResultMap">
select * from web_user where user_name = #{userName,jdbcType=VARCHAR}
</select>
</mapper>
4:启动服务验证
使用Postman 访问我们编写的http接口 http://localhost:8888/web_user/login
访问登录接口用户密码正确返回true
5:总结
Springboot与MyBatis-Plus的集成是很简单的,MyBatis-Plus相对于MyBatis做了跟多的封装和优化,是程序员跟多的去关注自己的业务功能。
但是一般我们使用MyBatis-Plus并不是项目创建就开始使用MyBatis-Plus。一般是项目已经开发好了。甚至上线了为了开发效率和代码的优雅需要选择 集成MyBatis-Plus。
编写一个单纯的Springboot与MyBatis-Plus项目去了解和学习还是很有必要的。
由于MyBatis-Plus自己提供了许多很好的API封装,上面的通过xml编写sql语句其实我们也可以省掉直接使用MyBatis-Plus提供的相关接口,甚至一些简单的分页查询我们也不需要编写sql,直接使用MyBatis-Plus的API就可以解决。
下一篇我们来讲解一下关于这一部分的高级特性,让你在工作编码中大大提高效率
代码放在https://gitee.com/liaohaoran520/mybatis-plus-breakthrough 有需要的可以前往下载