我将 Spring Data R2DBC 与 MySQL 结合使用,在将 INT 类型的数据库列映射到实体中的布尔字段时,我遇到了类型转换问题。
实体定义:
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
@Table("users")
public class UserEntity {
@Id
private Long id;
@Column("sms_list")
private Boolean smsPermited;
public Boolean getSmsList() {
return this.smsPermited;
}
public void setSmsList(Boolean smsPermited) {
this.smsPermited = smsPermited;
}
public Boolean getSmsPermited() {
return smsPermited;
}
public void setSmsPermited(Boolean smsPermited) {
this.smsPermited = smsPermited;
}
}
数据库架构:
CREATE TABLE users (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
sms_list INT(11) NOT NULL DEFAULT 0
);
运行应用程序时,我遇到以下错误:
No converter found capable of converting from type [java.lang.Integer] to type [java.lang.Boolean]
Spring Data R2DBC 似乎不会自动将 INT 数据库列转换为我的实体中的布尔值。
我尝试过的:
1.在Getter上使用@Column:
2.手动处理Getter/Setter中的转换::
3.全球转换器:::
预期行为
我想要:
问题:
Spring Boot 和库版本:
将 SMSPermission 设置为 int,然后在实体中创建一个新方法,如下所示
public Boolean getSmsListAsBoolean() {
// use this.smsPermitted to apply your logic how to convert int from
// db to boolean
}
您的整个实体将如下所示:
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
@Table("users")
public class UserEntity {
@Id
private Long id;
@Column("sms_list")
private Boolean smsPermited;
public Boolean getSmsList() {
return this.smsPermited;
}
public void setSmsList(Boolean smsPermited) {
this.smsPermited = smsPermited;
}
public Boolean getSmsPermited() {
return smsPermited;
}
public void setSmsPermited(Boolean smsPermited) {
this.smsPermited = smsPermited;
}
public Boolean getSmsListAsBoolean() {
// use this.smsPermitted to apply your logic how to convert int from
// db to boolean
}