SpringBoot除了可以集成JPA,还可以集成MyBatis。
MyBatis专注于SQL本身,是一个足够灵活的DAO层解决方案。
对性能的要求很高,或者需求变化较多的项目,如互联网项目,MyBatis将是不错的选择。
1、注解
@Mapper
public interface UserMapper {
/**
* keyProperty: 表示将select返回值设置到该属性中
* resultType: 返回类型
* before: 是否在insert之前执行
* statement: 自定义子查询
* @param userBase
*/
@SelectKey(keyProperty = "userBase.id",resultType = String.class, before = true,
statement = "select replace(uuid(), '-', '')")
@Options(keyProperty = "userBase.id", useGeneratedKeys = true)
@Insert("insert into user_base(id, " +
"name, " +
"passwd, " +
"phone " +
") values (#{userBase.id}, " +
"#{userBase.name}, " +
"#{userBase.password}, " +
"#{userBase.phone}" +
") "
)
public void insertForReg(@Param("userBase")UserBase userBase);
@Delete("DELETE FROM user WHERE id =#{id}") void delete(Long id);
}
简化了配置,也更符合Spring Boot的初衷。
2、配置文件
编写Mapper
@Mapper public interface UserMapper { int insert(@Param("pojo") User pojo); int insertList(@Param("pojos") List<User> pojo); int update(@Param("pojo") User pojo); }
编写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.wang.mybatis.UserMapper"> <!--auto generated Code--> <resultMap id="AllColumnMap" type="com.wang.mybatis.User"> <result column="id" property="id"/> <result column="name" property="name"/> <result column="hobby" property="hobby"/> </resultMap> <!--auto generated Code--> <sql id="all_column"> `id`, `name`, `hobby` </sql> <!--auto generated Code--> <insert id="insert"> INSERT INTO `user` (`id`,`name`,`hobby`) VALUES (#{pojo.id},#{pojo.name},#{pojo.hobby}) </insert> <!--auto generated Code--> <insert id="insertList"> INSERT INTO `user`( <include refid="all_column"/> )VALUES <foreach collection="pojos" item="pojo" index="index" separator=","> ( #{pojo.id}, #{pojo.name}, #{pojo.hobby} ) </foreach> </insert> <!--auto generated Code--> <update id="update"> UPDATE `user` <set> <if test="pojo.id != null"> `id` = #{pojo.id}, </if> <if test="pojo.name != null"> `name` = #{pojo.name}, </if> <if test="pojo.hobby != null"> `pwd` = #{pojo.hobby} </if> </set> WHERE `id` = #{pojo.id} </update> </mapper>
配置
mybatis: mapper-locations: classpath*:mapper/*Mapper.xml type-aliases-package: com.wang.mybatis
总结:xml方式比较繁琐,可读性可维护性不强。自动化插件MyBatisCodeHelper可以帮助提高开发效率。