簡體   English   中英

如何使用復合 kays(Kotlin、Spring 引導)創建實體 class

[英]How to create Entity class with composite kays (Kotlin, Spring boot)

我有一個數據庫圖,我需要在實體類中實現它

圖表圖像

用戶實體:

@Entity
class User (
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val idUser: Int = -1,
    @Column(unique=true)
    val name: String = "",
    @Column(unique=true)
    val email: String = "",
    @Column(nullable = false)
    val password: String = ""
)

帖子實體: 用戶實體:

@Entity
data class Post (
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val idPost: Int = -1,
    @Column(nullable = false)
    val title: String = "",
    @Column(nullable = false)
    val body: String = "",
    @Column(nullable = false)
    val date: String = Date().toString()
)

我只是不明白如何組織表之間的關系。 當表沒有主鍵時,IDEA 也會報錯。

幫助我實現 UserPost 實體 class。

您可以使用所需的詳細信息定義您的實體,例如屬性上的@columns和其他詳細信息。

以下課程僅供參考和指導。 請閱讀有關復合鍵的更多信息並參考鏈接https://www.baeldung.com/jpa-composite-primary-keys

@Entity
@IdClass(UserPost.class)
public class Post {
    @Id
    private int idPost;
    @Id
    private int idUser;

    private String title;
    private String body;
    private LocalDateTime date;

}

@Entity
@IdClass(UserPost.class)
class User{
    @Id
    private int idPost;
    @Id
    private int idUser;
    private String name;
    private String email;
    private String password;

}


class UserPost implements Serializable {
    private static final long serialVersionUID = 1L;

    private int idPost;
    private int idUser;

    //No-Args constructor and All-Args constructor
    //hashcode
    //equals
}

它在 java 中,在 kotlin 中不會有太大差異。 還有另一種使用@Embeddable and @EmbeddableID實現復合鍵的方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM