springboot整合mybatis
Posted 全他吗被取了
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot整合mybatis相关的知识,希望对你有一定的参考价值。
一、引入相关依赖
<dependencies>
<!--springboot web依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis分页插件,同时依赖了mybatis-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
<!--mybatis代码自动生成依赖-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.2</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--springboot测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
二、添加application.yml配置
server:
port: 9090
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/testdata?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: 123456
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:mapper/*.xml
三、添加mybatisgenerator.xml代码生成器配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--如果有外部引用,可以像下面这样引入外部配置文件-->
<!--<properties resource="generator.properties"/>-->
<context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 为模型生成序列化方法-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<!-- 为生成的Java模型创建一个toString方法 -->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!--可以自定义生成model的代码注释-->
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!--配置数据库连接-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/testdata?useUnicode=true;characterEncoding=utf8;serverTimezone=Asia/Shanghai"
userId="root"
password="123456">
<!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题-->
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<!--指定生成model的路径-->
<javaModelGenerator targetPackage="com.zhenghe.model" targetProject="src/main/java"/>
<!--指定生成mapper.xml的路径-->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
<!--指定生成mapper接口的的路径-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.zhenghe.mapper"
targetProject="src/main/java"/>
<!--生成全部表tableName设为%-->
<table tableName="sys_user">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="sys_role">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="sys_menu">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="sys_user_role">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="sys_role_menu">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
四、编写代码生成器的main启动类
public class MybatisGenerator
public static void main(String[] args) throws Exception
//MBG 执行过程中的警告信息
List<String> warnings = new ArrayList<String>();
//当生成的代码重复时,覆盖原代码
boolean overwrite = true;
//读取我们的 MBG 配置文件
InputStream is = BeanCopier.Generator.class.getResourceAsStream("/mybatisgenerator.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close();
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
//创建 MBG
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
//执行生成代码
myBatisGenerator.generate(null);
//输出警告信息
for (String warning : warnings)
System.out.println(warning);
五、运行启动类,即可生成对应的model,mapper和xml
public class SysUser implements Serializable
private Long id;
private String username;
private String password;
private String avatar;
private String email;
private String city;
private Date created;
private Date updated;
private Date lastLogin;
private Integer statu;
private static final long serialVersionUID = 1L;
public Long getId()
return id;
public void setId(Long id)
this.id = id;
public String getUsername()
return username;
public void setUsername(String username)
this.username = username;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
public String getAvatar()
return avatar;
public void setAvatar(String avatar)
this.avatar = avatar;
public String getEmail()
return email;
public void setEmail(String email)
this.email = email;
public String getCity()
return city;
public void setCity(String city)
this.city = city;
public Date getCreated()
return created;
public void setCreated(Date created)
this.created = created;
public Date getUpdated()
return updated;
public void setUpdated(Date updated)
this.updated = updated;
public Date getLastLogin()
return lastLogin;
public void setLastLogin(Date lastLogin)
this.lastLogin = lastLogin;
public Integer getStatu()
return statu;
public void setStatu(Integer statu)
this.statu = statu;
@Override
public String toString()
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", username=").append(username);
sb.append(", password=").append(password);
sb.append(", avatar=").append(avatar);
sb.append(", email=").append(email);
sb.append(", city=").append(city);
sb.append(", created=").append(created);
sb.append(", updated=").append(updated);
sb.append(", lastLogin=").append(lastLogin);
sb.append(", statu=").append(statu);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
public interface SysUserMapper
long countByExample(SysUserExample example);
int deleteByExample(SysUserExample example);
int deleteByPrimaryKey(Long id);
int insert(SysUser row);
int insertSelective(SysUser row);
List<SysUser> selectByExample(SysUserExample example);
SysUser selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("row") SysUser row, @Param("example") SysUserExample example);
int updateByExample(@Param("row") SysUser row, @Param("example") SysUserExample example);
int updateByPrimaryKeySelective(SysUser row);
int updateByPrimaryKey(SysUser row);
<?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.zhenghe.mapper.SysUserMapper">
<resultMap id="BaseResultMap" type="com.zhenghe.model.SysUser">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="avatar" jdbcType="VARCHAR" property="avatar" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="city" jdbcType="VARCHAR" property="city" />
<result column="created" jdbcType="TIMESTAMP" property="created" />
<result column="updated" jdbcType="TIMESTAMP" property="updated" />
<result column="last_login" jdbcType="TIMESTAMP" property="lastLogin" />
<result column="statu" jdbcType="INTEGER" property="statu" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and $criterion.condition
</when>
<when test="criterion.singleValue">
and $criterion.condition #criterion.value
</when>
<when test="criterion.betweenValue">
and $criterion.condition #criterion.value and #criterion.secondValue
</when>
<when test="criterion.listValue">
and $criterion.condition
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#listItem
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and $criterion.condition
</when>
<when test="criterion.singleValue">
and $criterion.condition #criterion.value
</when>
<when test="criterion.betweenValue">
and $criterion.condition #criterion.value and #criterion.secondValue
</when>
<when test="criterion.listValue">
and $criterion.condition
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#listItem
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, username, password, avatar, email, city, created, updated, last_login, statu
</sql>
<select id="selectByExample" parameterType="com.zhenghe.model.SysUserExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from sys_user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by $orderByClause
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from sys_user
where id = #id,jdbcType=BIGINT
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from sys_user
where id = #id,jdbcType=BIGINT
</delete>
<delete id="deleteByExample" parameterType="com.zhenghe.model.SysUserExample">
delete from sys_user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.zhenghe.model.SysUser">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into sys_user (username, password, avatar,
email, city, created,
updated, last_login, statu
)
values (#username,jdbcType=VARCHAR, #password,jdbcType=VARCHAR, #avatar,jdbcType=VARCHAR,
#email,jdbcType=VARCHAR, #city,jdbcType=VARCHAR, #created,jdbcType=TIMESTAMP,
#updated,jdbcType=TIMESTAMP, #lastLogin,jdbcType=TIMESTAMP, #statu,jdbcType=INTEGER
)
</insert>
<insert id="insertSelective" parameterType="com.zhenghe.model.SysUser">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into sys_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="username != null">
username,
</if>
<if test="password != null">
password,
</if>
<if test="avatar != null">
avatar,
</if>
<if test="email != null">
email,
</if>
<if test="city != null">
city,
</if>
<if test="created != null">
created,
</if>
<if test="updated != null">
updated,
</if>
<if test="lastLogin != null">
last_login,
</if>
<if test="statu != null">
statu,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="username != null">
#username,jdbcType=VARCHAR,
</if>
<if test="password != null">
#password,jdbcType=VARCHAR,
</if>
<if test="avatar != null">
#avatar,jdbcType=VARCHAR,
</if>
<if test="email != null">
#email,jdbcType=VARCHAR,
</if>
<if test="city != null">
#city,jdbcType=VARCHAR,
</if>
<if test="created != null">
#created,jdbcType=TIMESTAMP,
</if>
<if test="updated != null">
#updated,jdbcType=TIMESTAMP,
</if>
<if test="lastLogin != null">
#lastLogin,jdbcType=TIMESTAMP,
</if>
<if test="statu != null">
#statu,jdbcType=INTEGER,
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.zhenghe.model.SysUserExample" resultType="java.lang.Long">
select count(*) from sys_user
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update sys_user
<set>
<if test="row.id != null">
id = #row.id,jdbcType=BIGINT,
</if>
<if test="row.username != null">
username = #row.username,jdbcType=VARCHAR,
</if>
<if test="row.password != null">
password = #row.password,jdbcType=VARCHAR,
</if>
<if test="row.avatar != null">
avatar = #row.avatar,jdbcType=VARCHAR,
</if>
<if test="row.email != null">
email = #row.email,jdbcType=VARCHAR,
</if>
<if test="row.city != null">
city = #row.city,jdbcType=VARCHAR,
</if>
<if test="row.created != null">
created = #row.created,jdbcType=TIMESTAMP,
</if>
<if test="row.updated != null">
updated = #row.updated,jdbcType=TIMESTAMP,
</if>
<if test="row.lastLogin != null">
last_login = #row.lastLogin,jdbcType=TIMESTAMP,
</if>
<if test="row.statu != null">
statu = #row.statu,jdbcType=INTEGER,
</if>
</set>
<if test="example != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update sys_user
set id = #row.id,jdbcType=BIGINT,
username = #row.username,jdbcType=VARCHAR,
password = #row.password,jdbcType=VARCHAR,
avatar = #row.avatar,jdbcType=VARCHAR,
email = #row.email,jdbcType=VARCHAR,
city = #row.city,jdbcType=VARCHAR,
created = #row.created,jdbcType=TIMESTAMP,
updated = #row.updated,jdbcType=TIMESTAMP,
last_login = #row.lastLogin,jdbcType=TIMESTAMP,
statu = #row.statu,jdbcType=INTEGER
<if test="example != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.zhenghe.model.SysUser">
update sys_user
<set>
<if test="username != null">
username = #username,jdbcType=VARCHAR,
</if>
<if test="password != null">
password = #password,jdbcType=VARCHAR,
</if>
<if test="avatar != null">
avatar = #avatar,jdbcType=VARCHAR,
</if>
<if test="email != null">
email = #email,jdbcType=VARCHAR,
</if>
<if test="city != null">
city = #city,jdbcType=VARCHAR,
</if>
<if test="created != null">
created = #created,jdbcType=TIMESTAMP,
</if>
<if test="updated != null">
updated = #updated,jdbcType=TIMESTAMP,
</if>
<if test="lastLogin != null">
last_login = #lastLogin,jdbcType=TIMESTAMP,
</if>
<if test="statu != null">
statu = #statu,jdbcType=INTEGER,
</if>
</set>
where id = #id,jdbcType=BIGINT
</update>
<update id="updateByPrimaryKey" parameterType="com.zhenghe.model.SysUser">
update sys_user
set username = #username,jdbcType=VARCHAR,
password = #password,jdbcType=VARCHAR,
avatar = #avatar,jdbcType=VARCHAR,
email = #email,jdbcType=VARCHAR,
city = #city,jdbcType=VARCHAR,
created = #created,jdbcType=TIMESTAMP,
updated = #updated,jdbcType=TIMESTAMP,
last_login = #lastLogin,jdbcType=TIMESTAMP,
statu = #statu,jdbcType=INTEGER
where id = #id,jdbcType=BIGINT
</update>
</mapper>
六、在启动类上添加mapper包扫描
@SpringBootApplication
@MapperScan("com.zhenghe.mapper")
public class ZhengheApplication
public static void main(String[] args)
SpringApplication.run(ZhengheApplication.class,args);
七、单元测试并通过pageHelper进行简单分页
@Test
public void test2()
//页码
Integer pageNum = 1;
//每页数量
Integer pageSize = 3;
//将PageHelper.startPage(pageNum,pageSize)放在查询分页sql的方法前即可自动分页
PageHelper.startPage(pageNum,pageSize);
ResultVo resultVo = userService.selectUserList();
System.out.println(resultVo.getData());
SpringBoot 整合其他框架 -- SpringBoot整合Mybatis
1. SpringBoot整合Mybatis
需求:
SpringBoot整合MyBatis。
实现步骤:
- 搭建SpringBoot工程
- 引入mybatis起步依赖,添加mysql驱动
- 编写DataSource和MyBatis相关配置
- 定义表和实体类
- 编写dao和mapper文件/纯注解开发
- 测试
1.0 公共步骤
1.0.1 搭建SpringBoot工程
1.0.2 引入mybatis起步依赖 添加mysql驱动
pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.25</version>
</dependency>
1.0.3 搭建数据库环境
navicat运行下面的sql语句即可
CREATE DATABASE `springboot`;
USE `springboot`;
/*Table structure for table `t_user` */
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`password` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*Data for the table `t_user` */
insert into `t_user`(`id`,`username`,`password`) values (1,'zhangsan','123'),(2,'lisi','234');
1.0.4 配置数据库连接信息
# datasource
spring:
datasource:
# /// 表示省略了127.0.0.0.1
url: jdbc:mysql:///springboot?serverTimezone=UTC
username: root
password: 317525
driver-class-name: com.mysql.cj.jdbc.Driver
1.0.5 创建实体类
package com.tian.pojo;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\\'' +
", password='" + password + '\\'' +
'}';
}
}
1.1 注解开发
1.1.1 创建Mapper
package com.tian.mapper;
import com.tian.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
// Mapper表示在Mybatis中注册
@Mapper
// Repository表示当前类是持久层
@Repository
public interface UserMapper {
@Select("select * from t_user")
public List<User> findAll();
}
1.1.2 测试代码:
package com.tian;
import com.tian.mapper.UserMapper;
import com.tian.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class SpringbootMybatisApplicationTests {
@Test
void contextLoads() {
}
@Autowired
private UserMapper userMapper;
@Test
public void testFindAll() {
List<User> list = userMapper.findAll();
System.out.println(list);
}
}
运行结果:
1.2 传统xml映射文件开发
1.2.1 创建Mapper
package com.tian.mapper;
import com.tian.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
// Mapper表示在Mybatis中注册
@Mapper
// Repository表示当前类是持久层
@Repository
public interface UserXmlMapper {
public List<User> findAll();
}
1.2.2 创建Mapper映射文件
<?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.tian.mapper.UserXmlMapper">
<select id="findAll" resultType="user">
select *
from t_user
</select>
</mapper>
1.2.3 配置文件中注册xml文件
# datasource
spring:
datasource:
url: jdbc:mysql:///springboot?serverTimezone=UTC
username: root
password: 317525
driver-class-name: com.mysql.cj.jdbc.Driver
# mybatis
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml # mapper映射文件路径
type-aliases-package: com.tian.pojo # 配置别名
# config-location: # 指定mybatis的核心配置文件
1.2.4 测试代码:
package com.tian;
import com.tian.mapper.UserXmlMapper;
import com.tian.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class SpringbootMybatisApplicationTests {
@Test
void contextLoads() {
}
@Autowired
private UserXmlMapper userXmlMapper;
@Test
public void testFindAll() {
List<User> list = userXmlMapper.findAll();
System.out.println(list);
}
}
运行结果:
以上是关于springboot整合mybatis的主要内容,如果未能解决你的问题,请参考以下文章
企业分布式微服务云SpringCloud SpringBoot mybatis (十三)Spring Boot整合MyBatis
SpringBoot整合Mybatis方式2:使用注解方式整合Mybatis