java - 如何在sping jpa中使用转换器
问题描述
为了运行应用程序,我在战争中使用了 tomcat 8.5.50 包。我使用弹簧 5.2 版本。在我的代码中,我想像这样使用 LocalDataTime:
@Entity
@Table(name="meals")
public class Meal {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "date_time")
@Convert(converter = MealConverter.class)
private LocalDateTime datetime;
@Column(name = "description")
private String description;
@Column(name = "calories")
private int calories;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public LocalDateTime getDatetime() {
return datetime;
}
public void setDatetime(LocalDateTime datetime) {
this.datetime = datetime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCalories() {
return calories;
}
public void setCalories(int calories) {
this.calories = calories;
}
}
我的转换器:
@Converter(autoApply = true)
public class MealConverter implements AttributeConverter<Meal, String> {
private static final String SEPARATOR = ", ";
@Override
public String convertToDatabaseColumn(Meal meal) {
StringBuilder sb = new StringBuilder();
sb.append(meal.getCalories()).append(SEPARATOR)
.append(meal.getDatetime())
.append(SEPARATOR)
.append(meal.getDescription());
return sb.toString();
}
@Override
public Meal convertToEntityAttribute(String dbData) {
String[] rgb = dbData.split(SEPARATOR);
Meal meal = new Meal(Integer.valueOf(rgb[0]),
LocalDateTime(valueOf(rgb[1]),
rgb[2],
rgb[3]);
return meal;
}
}
我试图在 convertToEntityAttribute 方法中使用转换器,但编译器不允许我这样做。我的转换器需要修复什么?
解决方案
Meal meal = new Meal(Integer.valueOf(rgb[0]),
LocalDateTime(valueOf(rgb[1]),
rgb[2],
rgb[3]);
- 您的
Meal
类似乎没有任何显式构造函数,因此您无法将参数传递给new Meal()
. 您似乎试图传递两个论点。您可能想要创建一个合适的构造函数,或者您可能想要Meal
在创建对象后将这两个值传递给 using setter。 LocalDateTime
是一个类,但您似乎尝试将其作为具有三个参数的方法来调用。如果是这样java.time.LocalDateTime
,您可能打算这样做,但该类LocalDateTime.of(someArguemts)
没有任何三参数方法。of
如果您更好地解释您期望的结果,我们可以更好地指导您。- 作为您的第一个参数,
LocalDateTime
您调用了一个valueOf
似乎没有在您的类中声明的方法。您可能已经打算Integer.valueOf
像上一行那样。 - 如果您尝试使用 RGB 值来初始化日期(不知道这可能有什么意义),请注意,如果您的 RGB 值上升到 255,这可能会失败并出现异常,因为月份数字只会上升到 12 和一个月中的第 31 天。
我不确定以下内容是否正确或是否符合您的要求,但这是对您可能追求的目标的猜测。
@Override
public Meal convertToEntityAttribute(String dbData) {
String[] fields = dbData.split(SEPARATOR);
Meal meal = new Meal();
meal.setCalories(Integer.parseInt(fields[0]));
meal.setDateTime(LocalDateTime.parse(fields[1]));
meal.setDescription(fields[2]);
return meal;
}
我正在尝试与您的convertToDatabaseColumn
方法相反。我已经放弃了变量名rgb
,因为我没有看到它在这里不会产生误导。
推荐阅读
- c# - 将事件序列化为 JSON
- netbeans - 如何让 NetBeans 12.0 在 Mac 上启动(MAC OS 11.0 beta / Big Sur)
- reactjs - 如何在图表中的 x 轴上显示自定义值?
- python - Pycharm,安装下一个解释器后创建新项目时 SRE 模块不匹配
- docker - 无法在 Docker 中实现 WatchTower
- javascript - 使用 DOM 事件调用 Javascript 函数
- makefile - 如何编写多个文件夹makefile
- json - 按包名动态加载 json 文件(Typescript)
- javascript - QML 用 JavaScript 定义焦点链序列
- python - 如何按 Pandas 中重新设计的案例组对时间戳数据进行排序?