我想将DayOfWeek存储在我的PostgreSQL数据库中。因此,Im使用转换器将其存储为Integer。但是,如果您有更好的建议,我可以将其存储为其他数据类型。转换没有发生,因为我看不到我添加的错误打印。错误消息可以增强此功能。我是否需要更改原始存储库或我的错误在哪里?我的实体是:
@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 Im看起来像这样:
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
您的转换器没有任何问题。主要问题是您对存储库的查询。我已经在我的本地环境中对其进行了更改,它的工作原理就像是一种魅力。
我在本地查询上使用了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);
}
我已经假设了一个变量closeingTime,因为您发布的代码中没有它
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句