写在前面
本篇文章分享如何使用springboot集成mybatis-plus,并使用其代码生成器生成代码,继承其接口实现增删改查等。当然,也会分享我在其中踩到的坑,本文只是最基本最简单的使用,关于更高级的用法有空会再研究的。
在我看来,mybatis-plus最大的好处就是能让你的代码变得十分简洁,通过其提供的接口,我们在数据库层只需要实现比较复杂的select语句即可。以下是效果图(以变化比较明显的xml为例):
引入mybatis-plus前的EmployeeDao.xml:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.4//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yuan.oa.dao.EmployeeDao">
<resultMap id="Employee" type="com.yuan.oa.entity.Employee">
<id property="sn" column="sn" javaType="String"/>
<result property="password" column="password" javaType="String"/>
<result property="name" column="name" javaType="String"/>
<result property="departmentSn" column="department_sn" javaType="String"/>
<result property="post" column="post" javaType="String"/>
<association property="department" column="department_sn" javaType="Department">
<id property="sn" column="dsn" javaType="String"></id>
<result property="name" column="dname" javaType="String"></result>
</association>
</resultMap>
<insert id="insert" parameterType="Employee">
insert into employee values(#{
sn},#{
password},#{
name},#{
departmentSn},#{
post})
</insert>
<update id="update" parameterType="Employee">
update employee set password=#{
password},name=#{
name},department_sn=#{
departmentSn},post=#{
post} where sn=#{
sn}
</update>
<delete id="delete" parameterType="String">
delete from employee where sn=#{
sn}
</delete>
<select id="selectOne" parameterType="String" resultMap="Employee">
select e.*,d.sn dsn,d.name dname from employee e left join department d on d.sn=e.department_sn
where e.sn=#{
sn}
</select>
<select id="selectAll" resultMap="Employee">
select e.*,d.sn dsn,d.name dname from employee e left join department d on d.sn=e.department_sn
</select>
<select id="selectByDepartmentAndPost" resultMap="Employee">
select e.*,d.sn dsn,d.name dname from employee e left join department d on d.sn=e.department_sn
where e.sn is not null
<if test="dsn!=null">
and e.department_sn=#{
dsn}
</if>
<if test="post!=null">
and e.post=#{
post}
</if>
</select>
</mapper>
引入mybatis-plus后的EmployeeDao.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.yuan.oa_dao.dao.EmployeeDao">
<!-- 通用查询映射结果 -->
<resultMap id="EmployeeWithDepartment" type="com.yuan.oa_dao.dto.EmployeeWithDepartment">
<result column="sn" property="sn" />
<result column="password" property="password"/>
<result column="NAME" property="name" />
<result column="department_sn" property="departmentSn"<