方法一
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);
}
方法二
重写BeanPropertySqlParameterSource的getValue方法,当参数类型是枚举时返回枚举类对应的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);
}