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

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

问题是我的 UserRepository 使用 @RepositoryRestResource 时出现异常,它扩展了 JpaRepository.

原因是 findById 默认只接受 LongInt 类型,即使我有

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

我尝试搜索 Whosebug 和 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;

有什么建议吗?

非常感谢提前。很荣幸能在这里提问。

实体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;

您可以尝试这样的操作:

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "PR_KEY")
private String prKey;

如果你想阅读更多关于这个主题的内容,你可以开始看 throw here or here

您必须更改存储库中 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;
    //...

    }

应该是

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

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

根据最新版本的springdata jpa(2.1.10 GA),可以这样使用

这里是link

JpaRepository 是 CrudRepository 的特例。 JpaRepository 和 CrudRepository 都声明了两个类型参数,T 和 ID。您将需要提供这两种 class 类型。例如,

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

public interface UserRepository extends JpaRepository<XmppUser, java.lang.String> {
//..
}

注意第二个类型java.lang.String必须匹配主键属性的类型。在这种情况下,您不能将其指定为 StringInteger,而是 java.lang.String

尽量不要将自定义 class 命名为 String。使用 JDK.

中已经存在的相同 class 名称是不好的做法

我认为有办法解决这个问题。

比方说,Site 是我们的@Entity。

@Id
private String id;

getters setters

然后你可以调用 findById 如下

 Optional<Site> site = getSite(id);

注意:这对我有用,我希望它能帮助别人。