我想在我的DayOfWeek数据库中存储一个PostgreSQL。因此,我使用转换器存储它作为一个整数。但如果您有更好的建议,我可以将其存储为其他数据类型。转换没有进行,因为我没有看到我添加的错误打印。错误消息加强了这一点。我是否需要更改我的原始存储库,或者我的错误在哪里?我的实体是:
@Entity
@Table(name = "opening_hours")
public class OpeningHours {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column(name = "day")
@Convert(converter = DayOfWeekIntegerConverter.class)
private DayOfWeek day;
我使用的CrudRepository看起来是这样的:
public interface OpeningHoursRepository extends CrudRepository<OpeningHours, Long> {
@Query(value = "SELECT closing_time FROM opening_hours WHERE day = :day_of_week", nativeQuery = true)
LocalTime getShopClosingTimeOn(@Param("day_of_week") DayOfWeek dayOfWeek);
为了存储DayOfWeek,我使用以下转换器:
@Converter // I tried (autoapply=true) already but did not change anything
public class DayOfWeekIntegerConverter implements AttributeConverter<DayOfWeek, Integer> {
@Override
public Integer convertToDatabaseColumn(DayOfWeek attribute) {
System.err.println("converting dayofweek to int");
return attribute.getValue();
}
@Override
public DayOfWeek convertToEntityAttribute(Integer dbData) {
System.err.println("converting int to dayofweek ");
return DayOfWeek.of(dbData);
}
}
我的数据库表如下所示:
CREATE TABLE IF NOT EXISTS opening_hours
(
id BIGSERIAL NOT NULL PRIMARY KEY,
day INT
);
以下是错误:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
...
org.postgresql.util.PSQLException: ERROR: operator does not exist: integer = bytea
Hinweis: No operator matches the given name and argument types. You might need to add explicit type casts.
Position: 51
发布于 2019-11-01 18:14:29
你的转换器没什么问题。主要问题是您对存储库的查询。我已经在我当地的环境中改变了它,它就像一种魅力。
我在本机查询上使用了JQL
下面是我的代码
public interface OpeningHoursRepository extends CrudRepository<OpeningHours, Long> {
@Query(value = "SELECT closingTime FROM OpeningHours WHERE day = :day_of_week")
public LocalTime getShopClosingTimeOn(@Param("day_of_week") DayOfWeek dayOfWeek);
}
我假设变量是closingTime,因为post中的代码没有它
public class OpeningHours {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
private LocalTime closingTime;
@Column(name = "day")
@Convert(converter = DayOfWeekIntegerConverter.class)
private DayOfWeek day;
}
编辑:
,以防您想要坚持使用本机查询
然后编写存储库,如下所示
public interface OpeningHoursRepository extends CrudRepository<OpeningHours, Long> {
@Query(value = "SELECT closing_time FROM opening_hours WHERE day = :#{#day_of_week.getValue()}", nativeQuery = true)
public LocalTime getShopClosingTimeOn(@Param("day_of_week") DayOfWeek dayOfWeek);
}
发布于 2019-11-01 22:56:05
由于使用了Entity
注释,转换器类在@Convert
中工作,但是在存储库中,JPA无法将DayOfWeek参数转换为本地查询中的Integer。
更好的解决方案是编写JPQL查询,这样JPA将使用OpeningHours
类,它将看到DayOfWeek
参数与day
属性匹配,并进行转换。
https://stackoverflow.com/questions/58663485
复制相似问题