svili

相比之前的版本(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);
}

 

以上~

 

相关文章: