alexanoid
alexanoid

Reputation: 25892

Spring Data JPA ClassCastException: Integer cannot be cast to Long

In my Spring Data application I ran into the similar problem described here ClassCastException: Integer cannot be cast to Long, while trying to iterate over entity IDs

This my entity:

@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;
...
}

and Spring Data Repository method:

@Query(value = "SELECT u.user_id FROM users u WHERE u.game_id =:gameId", nativeQuery = true)
List<Long> getGameIds(@Param("gameId") Long gameId);

which is going to return List of Long type but after execution returns List of Integer and application fails with

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

How to tell Spring Data or JPA return List of Long(not Integer) in the result list ?

I don't want to cast values(Integer to Long) in run-time.

Also, the main criterion of my application is performance so is it a good idea to switch my IDs from Long to Integer in all my entities ? Is it a good practice to use Integer instead of Long in JPA for entity ID ?

UPDATED

I use PostgreSQL

In case of:

user_id INTEGER I'm receiving - java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

user_id BIGINT I'm receiving - java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

Upvotes: 4

Views: 6144

Answers (1)

asm0dey
asm0dey

Reputation: 2931

Problem is when you are using native query Long class doesn't corellate with your database type — getLong doesn't work there. So you should do one of the following

  1. Change type in db and in app to BigInteger (if integer is not enough for your needs)
  2. Change type in db and in app to Integer (if it's enough for your needs)
  3. Remove nqtiveQuery attribute and use clear JPQL.

Upvotes: 3

Related Questions