我想使用jdbi 3 @ColumnName批注来映射表和Java bean字段的列名,但是在运行时jdbi会引发异常。 我的问题是为什么会引发异常?我的用法不正确吗?如何解决这个问题呢? 谢谢
数据库表:
CREATE TABLE `department` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL DEFAULT '' ,
`business_system` tinyint(4) NOT NULL ,
`functional` tinyint(4) NOT NULL ,
`remark` varchar(100) NOT NULL DEFAULT ''
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Java Bean:
@Data
public class Department {
private Long id;
@NotNull
@Size(min = 3, max = 20)
private String name;
@NotNull
@ColumnName("business_system")
private Integer businessSystem;
@NotNull
@ColumnName("functional")
private Integer functional;
@Max(value = 200)
private String remark;
}
JDBI更新:
@Override
public Long create(Department department) {
String sql = "INSERT INTO department (name, business_system, functional, remark)"
+ "VALUES (:name, :business_system, :functional, :remark)";
return jdbi.withHandle(handle -> handle.createUpdate(sql)
.bindBean(department)
.executeAndReturnGeneratedKeys()
.mapTo(Long.class)
.findOnly());
}
单元测试运行结果:
org.jdbi.v3.core.statement.UnableToExecuteStatementException: Unable to
execute, no named parameter matches 'business_system'. [statement:"INSERT INTO
department (name, business_system, functional, remark)VALUES (:name,
:business_system, :functional, :remark)", rewritten:"INSERT INTO department
(name, business_system, functional, remark)VALUES (:name, :business_system,
:functional, :remark)", parsed:"ParsedSql{sql='INSERT INTO department (name,
business_system, functional, remark)VALUES (?, ?, ?, ?)',
parameters=ParsedParameters{positional=false, parameterNames=[name,
business_system, functional, remark]}}",
arguments:{ positional:{}, named:{}, finder:[{lazy bean property arguments
"Department(id=null, name=test, businessSystem=2, functional=2,
remark=test)"]}]
答案 0 :(得分:1)
Jdbi维护者在这里。四个误解共同导致您的代码无法正常工作:
首先,@ColumnName
定义了一种单向映射,仅用于将列名映射到对象属性/字段/构造函数参数。因此,BeanMapper
将使用@ColumnName
注释,但是bindBean()
会忽略它。
第二,BeanMapper
仅在获取器和设置器上检测到@ColumnName
,而不是字段。
由于您使用的是Lombok的@Data
批注,因此@ColumnName
批注实际上放在字段上。龙目岛(Lombok)有一种非常难看的方法来为getter或setter指定注释:
@NotNull
@Getter(onMethod=@__(@ColumnName("business_system")))
private Integer businessSystem;
@NotNull
@Getter(onMethod=@__(@ColumnName("functional")))
private Integer functional;
第三,bindBean()
绑定基于bean属性名称而不是列名称的命名参数。因此,您的命名参数应位于:camelCase
中,而不是:snake_case
中:
INSERT INTO department (name, business_system, functional, remark)
VALUES (:name, :businessSystem, :functional, :remark)
-- ^ camel case property name
最后,Jdbi 3已经将蛇形案例的列名与驼峰式属性名进行了匹配。例如:一列foo_bar
将自动映射到fooBar
属性,而无需@ColumnName
注释。