【发布时间】:2020-04-06 15:32:11
【问题描述】:
在名为PlayerPoints 的@Entity 类中,我有一个java.sql.Date 字段映射到一个MariaDB 数据库字段,其中有一列日期类型。当我使用查询方法通过JpaRepository 查询数据库时,它总是返回null。
这是我迄今为止尝试过的:
调用数据库:
PlayerPoints playerPointsFound = playerPointsRepository.findByDatePlayed(matchDay.getDate())
Optional<PlayerPoints> findByDatePlayed(Date matchDay); // Does not work
@Query(value = "SELECT * FROM player_points pp WHERE pp.date_played = ?1", nativeQuery = true)
Optional<PlayerPoints> myOwnFindByDatePlayed(Date matchDay); // Does not work
@Query(value = "SELECT * FROM player_points pp WHERE pp.date_played = '2020-06-12'", nativeQuery = true)
Optional<PlayerPoints> myOwnFindByFixedDatePlayed(); //WORKS!
在实体类中,我尝试添加@Type(type="date"),但它没有改变任何东西。我认为它绑定为Date,即使没有@Type 注释,这似乎是正确的:
o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [DATE] - [2020-06-12]
我的数据库已满:
*************************** 1. row ***************************
id: 165
date_played: 2020-06-12
player_points: 100
另外,我检查了列类型:
+-----------+
| DATA_TYPE |
+-----------+
| int |
| date |
| int |
+-----------+
我的表已经通过以下命令创建:
CREATE TABLE player_points (
id INT AUTO_INCREMENT PRIMARY KEY,
date_played DATE NOT NULL,
player_points INT NOT NULL,
);
有人知道为什么这个查询总是返回null吗?
更新!
我查看了我的 mariadb 的日志文件,发现在查询中硬编码日期时会导致:
SELECT * FROM player_points pp WHERE pp.date_played = '2020-06-12'
但是,使用 hibernate 的映射,我得到以下查询(不是日期):
select playerpoin0_.id as id1_1_, playerpoin0_.date_played as date_pla2_1_, playerpoin0_.player_points as player_poi_pl3_1_, from player_points playerpoin0_ where playerpoin0_.date_played='2020-06-11'
所以它与应用程序和 mariadb 服务器的时区有关。我没能解决这个问题,但离解决方案又近了一步。
问候,
巴特
【问题讨论】:
-
尾随的
1可能是"SELECT * FROM player_points pp WHERE pp.date_played = ?1"中的问题...这可以解释myOwnFindByDatePlayed(Date matchDay)的结果。 -
试过没有尾随
1没有成功。 -
@deHaar 表明 Spring 数据需要尾随 1,即
?1表示第一个位置参数。问题更有可能是时区之一,特别是因为一天可能会用时间 00:00:00,000 表示,因此任何时区差异都可能很容易导致 1 天的差异。 -
@Thomas 好的,谢谢...不知道 ;-)
标签: java spring spring-boot spring-data-jpa repository