Spring Boot JdbcTemplate 插入枚举类型

JdbcTemplate Spring Boot Java About 1,446 words

方法一

registerSqlType:适用于数据库存放的是字符串类型,枚举类型为单纯字段的。

枚举类

public enum PostStatus {

    AUDITING,

    AUDIT_PASS,

    AUDIT_FAILED,

    DELETED
}

具体实现

@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void insertRecord(Post post) {
    String sql = ...
    BeanPropertySqlParameterSource paramSource = new BeanPropertySqlParameterSource(post);
    //PostStatus枚举类对应数据库字段是status
    paramSource.registerSqlType("status", Types.VARCHAR);
    int result = namedParameterJdbcTemplate.update(sql, paramSource);
}

方法二

重写BeanPropertySqlParameterSourcegetValue方法,当参数类型是枚举时返回枚举类对应的int值。

枚举类

@Getter
@AllArgsConstructor
public enum TaskStatus {
    WAITING((short) 0, "等待"), 
    SUCCESS((short) 1, "成功"), 
    FAILED((short) 2, "失败"),
    DELETED((short) 3, "已删除");

    private short code;
    private String label;

}

具体实现

@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void insertRecord(Post post) {
    String sql = ...
    BeanPropertySqlParameterSource paramSource = new BeanPropertySqlParameterSource(post) {
        @Override
        public Object getValue(String paramName) throws IllegalArgumentException {
            Object value = super.getValue(paramName);
            if (value instanceof Enum) {
                return ((Enum) value).ordinal();
            }
            return value;
        }
    };
    int result = namedParameterJdbcTemplate.update(sql, paramSource);
}
Views: 4,540 · Posted: 2020-03-28

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh