为了运行应用程序,我在 war 中使用 tomcat 8.5.50 包。 我用的是spring 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()
。您似乎试图传递两个论点。您可能想创建一个合适的构造函数,或者您可能想在创建对象后使用 setter 将两个值传递到Meal
中。 LocalDateTime
是一个类,但您似乎尝试将其作为具有三个参数的方法来调用。如果是java.time.LocalDateTime
,您可能想要LocalDateTime.of(someArguemts)
,但没有任何三参数of
方法那个类(class)的。如果您更好地解释您期望的结果,我们可以更好地指导您。- 作为
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
,因为我不明白它如何不会在这里产生误导。
关于java - 如何在spring jpa中使用to转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60899851/