Creating a Post entity

Create a Post entity named Post.kt with the @Entity annotation to convert this class into an entity class. Here is the code of this model class:

@Entity
class Post(text: String, postedBy: Profile) : Serializable {

@Id
@GeneratedValue
var id: Long? = 0

var text: String? = text

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "profile_id")
@JsonIgnoreProperties("username","password", "email","accCreatedTime","firstName","lastName",
"contactNumber","dob","city","country")
var postedBy: Profile? = postedBy

@JsonIgnore
@JsonProperty("postCreatedTime")
var postCreatedTime: Instant? = Instant.now()

@OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY, orphanRemoval=true)
val comments = mutableListOf<Comment>()


@OneToMany(cascade = [CascadeType.ALL], orphanRemoval = true)
var likes: List<LikeObj>? = mutableListOf<Comment>()
}

Here we have two elements and one constructor. Here is the constructor:

@Entity
class Post(text: String, postedBy: Profile) : Serializable {
-----
-----
}

It's time now to discuss some new annotations that have been used in this class:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "profile_id")
@JsonIgnoreProperties("username","password", "email","accCreatedTime","firstName","lastName",
"contactNumber","dob","city","country")

var postedBy: Profile? = postedBy

@ManyToOne on the Profile variable means that this will indicate which user posted that specific status. 

@JoinColumn means its access element Profile is connected with the foreign key using profile_id.

@JsonIgnoreProperties(......) ignores the JSON properties during deserialization. In this project, when you get the post's JSON, in the profile attribute you will only find the id. Here is a simple example of a JSON:

 

You can see "id":0, which is the id of the post.

Now create a mutable list of the Comment and annotate it with @OneToMany, as follows:

 @OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.LAZY, orphanRemoval=true)
val comments = mutableListOf<Comment>()

@OneToMany(....) means a post can be many comments and likes. 

cascade = [CascadeType.ALL] attribute is a feature of Hibernate. It means you can apply all primary cascade types.

fetch = FetchType.LAZY means it fetches the data lazily during the first access.

orphanRemoval=true means if the post has been deleted, then all the comments and likes on this post will be deleted automatically.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.202.61