首页 > 解决方案 > 可以在Bean上写MyBatis映射注解

问题描述

在 MyBatis 中,应该这样使用,代码太多而且看起来很不优雅:

@Mapper
public interface SeqMapper {

    @Select("select * FROM COMMON_SEQ WHERE APP_CODE = #{appCode} FOR UPDATE")
    @Results(id = "seqDOMap", value = {
            @Result(column = "APP_CODE", property = "appCode"),
            @Result(column = "SEQ", property = "seq"),
            @Result(column = "STEP", property = "step"),
            @Result(column = "SEQ_MAX", property = "seqMax"),
            @Result(column = "UPDATED_TIME", property = "updatedTime"),
            @Result(column = "BEFORE_UPDATED_TIME", property = "beforeUpdatedTime"),
            @Result(column = "RESET_TIME", property = "resetTime"),
    })
    SeqDO selectForUpdate(SeqDO seqDO);
public class SeqDO {
    private Integer appCode;
    private Long seq;
    private Long step;
    private Long seqMax;
    private Date updatedTime;
    private Date beforeUpdatedTime;
    private Date resetTime;

我会这样使用,简洁美观:

public class SeqDO {

    @Result("APP_CODE")
    private Integer appCode;

    @Result("SEQ")
    private Long seq;

    @Result("STEP")
    private Long step;

    @Result("SEQ_MAX")
    private Long seqMax;

    @Result("UPDATED_TIME")
    private Date updatedTime;

    @Result("BEFORE_UPDATED_TIME")
    private Date beforeUpdatedTime;

    @Result("RESET_TIME")
    private Date resetTime;

朋友说可以用“as”,这样也符合不使用“select *”的规范,也可以。

如果可以在现场写,请回答。

@Mapper
public interface SeqMapper {

    @Select("select " +
            "APP_CODE as appCode, " +
            "SEQ as seq, " +
            "STEP as step, " +
            "SEQ_MAX as seqMax, " +
            "UPDATED_TIME as updatedTime, " +
            "BEFORE_UPDATED_TIME as beforeUpdatedTime, " +
            "RESET_TIME as resetTime " +
            "FROM COMMON_SEQ WHERE APP_CODE = #{appCode} FOR UPDATE")
    SeqDO selectForUpdate(SeqDO seqDO);

(以下文字纯属补字数:)

我觉得xml里面的代码太多了,所以想用注解,注解在IDE中可以很方便的跳转。如果方式如下,跳转会更方便,字段名不需要再修改。

标签: mybatis

解决方案


我朋友说可以用mybatis plus:

https://baomidou.com/en/guide/annotation.html#tablefield


推荐阅读