x如何使用 Spring Data JPA 在 Spring 中为 CrudRepository 设置 @Id 字符串?

And*_*sev 3 java spring hibernate spring-data-jpa spring-hateoas

问题是我在使用@RepositoryRestResource我的UserRepository扩展时遇到了异常JpaRepository

原因是默认情况下findById只接受Long或输入Int,即使我有

@Id String id;而不是@Id Int id在我的实体定义中。

我尝试搜索 StackOverflow 和 Google,但没有找到任何解决方案。

错误信息如下:

"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\""

我想让它与

@Id String id;

有什么建议?

非常感谢提前。在这里提问是我的荣幸。

实体类:

@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;
Run Code Online (Sandbox Code Playgroud)

adm*_*635 5

您必须更改存储库上的 ID 类型以与实体上的 id 属性类型匹配。

基于

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

    }
Run Code Online (Sandbox Code Playgroud)

它应该是

public interface UserRepository extends CrudRepository<XmppUser, String> {
    //..
    }
Run Code Online (Sandbox Code Playgroud)

https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#findById-ID-