亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 206 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號