为了账号安全,请及时绑定邮箱和手机立即绑定

x如何使用 Spring Data JPA 在 Spring 中为 CrudRepository

x如何使用 Spring Data JPA 在 Spring 中为 CrudRepository

暮色呼如 2023-05-24 17:38:20
@RepositoryRestResource问题是我在使用for my UserRepositorythat extends 时遇到异常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;
查看完整描述

4 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

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


来自 Spring 文档:


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

基于


@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> {

    //..

    }


查看完整回答
反对 回复 2023-05-24
?
jeck猫

TA贡献1909条经验 获得超7个赞

我认为有一种方法可以解决这个问题。

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

@Id
private String id;

getters setters

然后你可以调用 findById 如下

 Optional<Site> site = getSite(id);

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


查看完整回答
反对 回复 2023-05-24
?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

你可以尝试这样的事情:


@Id

@GeneratedValue(generator = "uuid")

@GenericGenerator(name = "uuid", strategy = "uuid2")

@Column(name = "PR_KEY")

private String prKey;

查看完整回答
反对 回复 2023-05-24
?
慕妹3146593

TA贡献1820条经验 获得超9个赞

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


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

//..

}

或者


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

//..

}

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


尽量不要将自定义类命名为String. 使用与 JDK 中已经存在的类名相同的类名是一种不好的做法。


查看完整回答
反对 回复 2023-05-24
  • 4 回答
  • 0 关注
  • 124 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信