I want to have add more tags to the post by this w...
# server
m
I want to have add more tags to the post by this way
Copy code
post.tags.add(existedTag)
postRepo.save(post)
but It didn't work
m
Send here your Post JPA entity (that owns the relationship)
m
this is my user-role case, It have the same issue
Copy code
@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
does it work with
saveAndFlush
? Do you use
@Transactional
?
m
I don't use @Transactional let me try with saveAndFlush
Transactional
doesn't work and I can't call
saveAndFlush
m
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:
Copy code
<http://existedTag.post|existedTag.post> = post
post.tags.add(existedTag)
postRepo.save(post)
👍 1
m
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
Copy code
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