Mybatis JPA 插件简介(v2.1.0)

介绍 MyBatis-JPA v2.1.0 的两大核心功能:符合 JPA 规范的 ResultMap 生成及简化 Insert/Update 语句构建。该版本针对 MyBatis 提供的 ResultSet 不够灵活、ResultMap 构建繁琐等问题进行了改进。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

相比之前的版本(v1.1.0),此版本(v2.1.0)做了较大的改动。

项目地址:

github https://github.com/cnsvili/mybatis-jpa

gitee https://gitee.com/svili/mybatis-jpa

当前版本主要提供2个功能:

1.生成符合JPA规范的ResultMap,支持结果集的嵌套;

2.简化Insert/Update语句的构建。

解决实际开发中的痛点:

1.Mybatis提供的ResultSet不够灵活,ResultMap构建繁琐;

2.Insert/Update构建繁琐,特别是cloumn列很多时,构建和修改都很麻烦。

~~~mybatis generator不符合我个人习惯,不做评价。

 

鉴于后续版本修改,可能导致文章与版本不一致,建议阅读代码仓库的wiki文档,本文只列举简单示例,说明版本特性。

1 ResultTypePlugin

e.g.

mybatis.xml

<configuration>
    <plugins>
    <plugin interceptor="com.mybatis.jpa.plugin.ResultTypePlugin">
    </plugin>
    </plugins>
</configuration>

JavaBean

@Entity
public class UserArchive {// <resultMap id="xxx" type="userArchive">

    @Id
    private Long userId;// <id property="id" column="user_id" />
                           
    /** 默认驼峰与下划线转换 */
    private String userName;// <result property="username" column="user_name"/>

    /** 枚举类型 */
    @Enumerated(EnumType.ORDINAL)
    private SexEnum sex;// <result property="sex" column="sex" typeHandler=EnumOrdinalTypeHandler/>

    /** 属性名与列名不一致 */
    @Column(name = "gmt_create")
    private Date createTime;// <result property="createTime" column="gmt_create"/>
}// </resultMap>

mapper.xml

<!-- in xml,declare the resultType -->
<!-- 使用resultType  -->
<select id="selectById" resultType="userArchive">
    SELECT * FROM t_sys_user_archive WHERE user_id = #{userId}
</select>

 

2 DefinitionStatementScanner

Spring 容器初始化完成后执行

@Service
public class DefinitionStatementInit {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @PostConstruct
    public void init() {
        Configuration configuration = sqlSessionFactory.getConfiguration();
        StatementBuildable statementBuildable = new DefinitionStatementBuilder(configuration);
        DefinitionStatementScanner.Builder builder = new DefinitionStatementScanner.Builder();
        DefinitionStatementScanner definitionStatementScanner = builder.configuration(configuration).basePackages(new String[]{"com.mybatis.jpa.mapper"})
                .statementBuilder(statementBuildable).build();
        definitionStatementScanner.scan();
    }
}

Mapper

@Mapper
@Repository
public interface UserUpdateMapper {

    @InsertDefinition(selective = true)
    int insert(User user);

    @UpdateDefinition(selective = true, where = " user_id = #{userId}")
    int updateById(User user);
}

 

以上~

 

转载于:https://www.cnblogs.com/svili/p/8871393.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值