Search code examples
javaspringhibernatespring-data-jpaspring-hateoas

xHow can I have @Id string for CrudRepository in Spring with Spring Data JPA?


The problem is that I am getting an exception using @RepositoryRestResource for my UserRepository that extends JpaRepository.

The reason for that is that findById is only accepting Long or Int types by default, even I have

@Id String id; and not @Id Int id in my entity definition.

I have tried searching StackOverflow and Google, but haven't found any solutions.

The error message is as follows:

"Failed to convert from type [java.lang.String] to type [java.lang.Integer] for value '3175433272470683'; nested exception is java.lang.NumberFormatException: For input string: \"3175433272470683\""

I want to make it work with a

@Id String id;

Any suggestions?

Many thanks in advances. It's a big privilege to ask questions here.

The Entity class:

@Entity // This tells Hibernate to make a table out of this class
@Table(name = "users")
public class XmppUser {
    @Id
    private java.lang.String username;

    private String password;
    private String serverkey;
    private String salt;
    private int iterationcount;
    private Date created_at;

    //    @Formula("ST_ASTEXT(coordinates)")
//    @Column(columnDefinition = "geometry")
//    private Point coordinates;
    //    private Point coordinates;
    private String full_name;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "username", nullable = true)
    private XmppLast xmppLast;

Solution

  • You must change the type of the ID type parameter in the repository to match with the id attribute type on your entity.

    From the Spring docs:

    Interface Repository<T,ID>
    Type Parameters:
      T - the domain type the repository manages    
      ID - the type of the id of the entity the repository manages
    

    Based on

    @Entity // This tells Hibernate to make a table out of this class
    @Table(name = "users")
    public class XmppUser {
        @Id
        private java.lang.String username;
        //...
    
        }
    

    It should be

    public interface UserRepository extends CrudRepository<XmppUser, String> {
        //..
        }
    

    See: