Persist OneToOne relation with SpringData JPA

前端 未结 1 362
时光说笑
时光说笑 2020-12-31 14:43

I have the next two entities with a OneToOne relation between them:

@Entity
@Table(name = \"tasks\")
public class Task {
    @OneToOne(mappedBy = \"task\", c         


        
相关标签:
1条回答
  • 2020-12-31 15:19

    Here we go again.

    Every bidirectional association has two sides : the owner side, and the inverse side. The inverse side is the one which has the mappedBy attribute. The owner side is the other one. JPA/Hibernate only cares about the owner side. So if you just initialize the inverse side, the association won't be persisted.

    It's a good practice, generally, to initialize both sides of the association. First because it makes sure the owner side is initialized, and second because it makes the graph of entities coherent, for your own good.

    Also note that if you're working inside a transaction (and you should), all the entities returned by your queries are attached entities. The changes applied to the entities are automatically made persistent when the transaction is committed (or before). There is no need to save the entities explicitely like you're doing.

    0 讨论(0)
提交回复
热议问题