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