Spring Boot JdbcTemplate插入枚举类型
JdbcTemplateSpring BootJava大约 1445 字方法一
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);
}
阅读 952 · 发布于 2020-03-28
————        END        ————
扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批
- Windows平台lua-resty-upload上传的文件无法打开阅读 131
- Spring Boot配置文件中设置List和Map阅读 1710
- OpenResty使用cjson操作JSON数据阅读 1580
- 走进Rust:流程控制阅读 263
- Java储存相同key的map阅读 586
- 软考-系统架构设计师:系统性能设计-性能指标阅读 440
- Android一键清理用户数据阅读 570
- HTML中使用datalist标签给输入框添加下拉框选项阅读 723
- OpenResty中使用ngx.share.DICT完成内存存储阅读 1231
- Spring Boot JPA控制台输出格式化后的SQL语句阅读 1898