4

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

7
  • 4
    Did you try to use not native query but JPQL, something like "select id from User where ..."? Commented May 9, 2016 at 9:00
  • Check the database type of the column for entityId, use appropriate type for column and compatible type for attribute in java class, then this won't appear. Commented May 9, 2016 at 9:01
  • which DB are you using Commented May 9, 2016 at 9:08
  • I'm using PostgreSQL. I have updated my question and added more info about my user_id datatype. Commented May 9, 2016 at 9:20
  • @Stan, JPQL works fine, thanks ! Is any chance to get it working with a native query also ? Commented May 9, 2016 at 9:32

1 Answer 1

3

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.