在我的 Spring Data 应用程序中,我遇到了此处描述的类似问题 ClassCastException: Integer cannot be cast to Long, while trying to iterate over entity IDs
这是我的实体:
@Table(name = "users")
public class User extends BaseEntity implements Serializable {
private static final long serialVersionUID = 5088960286161030648L;
@Id
@SequenceGenerator(name = "users_id_seq", sequenceName = "users_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.AUTO, generator = "users_id_seq")
private Long id;
...
}
和 Spring Data Repository 方法:
@Query(value = "SELECT u.user_id FROM users u WHERE u.game_id =:gameId", nativeQuery = true)
List<Long> getGameIds(@Param("gameId") Long gameId);
这将返回 Long 类型的列表,但在执行后返回 Integer 列表并且应用程序失败并显示
java.lang.ClassCastException: java.lang.Integer 无法转换为 java.lang.Long
如何告诉 Spring Data 或 JPA 在结果列表中返回 Long
(而不是 Integer
)的列表?
我不想在运行时转换值(整数到长整数)。
此外,我的应用程序的主要标准是性能,因此将我所有实体中的 ID 从 Long
切换为 Integer
是个好主意吗?在 JPA 中使用 Integer
而不是 Long
作为实体 ID 是一种好习惯吗?
已更新
我使用 PostgreSQL
如果是:
user_id INTEGER
我收到了 - java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
user_id BIGINT
我收到了 - java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
最佳答案
问题是当您使用 native 查询时 Long
类与您的数据库类型不相关——getLong 在那里不起作用。因此,您应该执行以下操作之一
- 将 db 和 app 中的类型更改为 BigInteger(如果整数不能满足您的需求)
- 将 db 和 app 中的类型更改为 Integer(如果它足以满足您的需求)
- 删除 nqtiveQuery 属性并使用清晰的 JPQL。
关于java - Spring 数据 JPA ClassCastException : Integer cannot be cast to Long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37111445/