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

Viewed 63

I have a database diagram, which i need to implement in Entity classes

Diagram image

User entity:

@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 = ""
)

Post entity: User entity:

@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()
)

I just don't understand how to organize a relationship between tables. Also IDEA reports an error when a table does not have Primary Key.

Help me with implementation of UserPost Entity class.

EDIT - 1

Okay, I have a solution, just add a data source (I used MySQL) and use Generate Kotlin Entities.kts then IDEA will automatically create all Entity classes. I think it is the most easy way. Generate Kotlin Entities.kts

1 Answers

You can define your entities as below with required details such as @columns on attributes and other details.

The below classes are just for reference and to guide on the path. Please read more about Composite keys and refer the link 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
}

Its in java, In kotlin there will not be much diffrence. There is another way to implement the composite key using @Embeddable and @EmbeddableID

Related