- New (Transient)
- Persistent (Managed)
- Detached
- Removed
https://vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-transitions/
- must only be used for new entities
- attaches an entity to the currently running persistence context
- is required only for detached entities
- reattaches the entity to a new Persistence Context
https://vladmihalcea.com/jpa-persist-and-merge/
class Post(
@Id
@GeneratedValue(strategy = GenerationType.UUID)
var id: UUID? = null,
val title: String,
@OneToMany(
cascade = [CascadeType.ALL],
orphanRemoval = true
)
@JoinColumn("post_id")
val comments: MutableList<Comment> = mutableListOf()
val content: String
)
class Comment(
@Id
@GeneratedValue(strategy = GenerationType.UUID)
var id: UUID? = null,
val content: String
)
insert into post (content,title,id) values (?,?,?)
insert into comment (content,id) values (?,?)
insert into comment (content,id) values (?,?)
insert into comment (content,id) values (?,?)
update comment set post_id=? where id=?
update comment set post_id=? where id=?
update comment set post_id=? where id=?
@Entity
class Post(
@Id
@GeneratedValue(strategy = GenerationType.UUID)
var id: UUID? = null,
val title: String,
val content: String,
@OneToMany(
mappedBy = "post",
cascade = [CascadeType.ALL],
orphanRemoval = true
)
val comments: MutableList<Comment> = mutableListOf()
) {
fun addComment(comment: Comment) {
comments.add(comment)
comment.post = this
}
fun removeComment(comment: Comment) {
comments.remove(comment)
comment.post = null
}
}
@Entity
class Comment(
@Id
@GeneratedValue(strategy = GenerationType.UUID)
val id: UUID? = null,
@ManyToOne(fetch = FetchType.LAZY)
var post: Post? = null,
val content: String
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Comment
return id != null && id == other.id
}
override fun hashCode(): Int = javaClass.hashCode()
}
insert into post (content,title,id) values (?,?,?)
insert into comment (content,post_id,id) values (?,?,?)
insert into comment (content,post_id,id) values (?,?,?)
insert into comment (content,post_id,id) values (?,?,?)
class Post(
@Id
@GeneratedValue(strategy = GenerationType.UUID)
var id: UUID? = null,
val title: String,
val content: String
)
class Comment(
@Id
@GeneratedValue(strategy = GenerationType.UUID)
var id: UUID? = null,
@ManyToOne(fetch = FetchType.LAZY)
val post: Post,
val content: String
)
@Entity
class Detail(
@Id
var id: UUID? = null,
val createdAt: LocalDateTime,
val createdBy: String,
@OneToOne(fetch = FetchType.LAZY)
@MapsId
val post: Post
)
https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/#:~:text=The%20best%20way%20to%20map%20a%20%40OneToOne%20relationship%20is%20to,using%20the%20Post%20entity%20identifier.&text=This%20way%2C%20the%20id%20property,Primary%20Key%20and%20Foreign%20Key. https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/