https://kotlinlang.org logo
Title
m

minhnhat

07/16/2022, 4:36 PM
I want to have add more tags to the post by this way
post.tags.add(existedTag)
postRepo.save(post)
but It didn't work
m

Mikhail

07/16/2022, 4:36 PM
Send here your Post JPA entity (that owns the relationship)
m

minhnhat

07/16/2022, 4:38 PM
this is my user-role case, It have the same issue
@Entity
class Userr {
    @Id
    @GeneratedValue
    var id: Long? = null

    var name: String? = null

    @OneToMany(mappedBy = "user", cascade = [CascadeType.PERSIST])
    var roles: MutableList<Role> = mutableListOf()
}

@Entity
class Role {
    @Id
    @GeneratedValue
    var id: Long? = null

    var name: String? = null

    @ManyToOne
    @JsonIgnore
    var user: Userr? = null
}
m

Mikhail

07/16/2022, 4:39 PM
does it work with
saveAndFlush
? Do you use
@Transactional
?
m

minhnhat

07/16/2022, 4:40 PM
I don't use @Transactional let me try with saveAndFlush
Transactional
doesn't work and I can't call
saveAndFlush
m

Mikhail

07/16/2022, 4:56 PM
I wouldn't use
@OneToMany
, because it's logically incorrect, a single post can have many tags and a tag itself can associate with multiple posts, this is
@ManyToMany
. But, try this:
<http://existedTag.post|existedTag.post> = post
post.tags.add(existedTag)
postRepo.save(post)
👍 1
m

minhnhat

07/17/2022, 7:23 AM
yes, you are right, I just demonstrate the issue. think about another example. User will have list of addresses how can I easy add new address to user
val newAddress = Address()
newAddress.user = user // redundant
user.addresses.add(newAddress)
userRepo.save(user)
but if this is the only way to work in kotlin, I'm ok BTW, thank you very much @Mikhail
what I'm missing is
JoinColumn
in
OneToMany
and
cascade = [CascadeType.All]
👍 1