简体   繁体   中英

Storing only one entity of bidirectional OneToOne relationship with Hibernate and Spring

Situation :

  • I'm using Spring (data) and Hibernate.
  • I have to entities with a bidirectional @OneToOne relationship.
  • Both share the same key (using @PrimaryKeyJoinColumn )

Problem :

  • I want load A and B from the database
  • I want to temporarily modify B (only in memory)
  • I want to do calculations on B
  • I want to store A, but not B

Formulated in code:

a = repositoryForA.findById(a);
b = a.getB();
a.setAttribute(abc);
b.setAttribute(xyz);
repositoryForA.save(a);

The behavior I see however is that always both A and B are stored (Verified with tests and hibernate log)

What I've tried :

  • Detaching B before saving A before: entityManager.detach(b); repository.save(a) entityManager.detach(b); repository.save(a)
  • No propagation @OneToOne(cascade={})
  • Set a.setB(null) and detach before saving

Is this possible? Is the relationship maybe not good for this purpose?

Entities :

@Entity
public class A {

    @Id
    @GeneratedValue
    protected Long id;

    @OneToOne
    @PrimaryKeyJoinColumn
    private B b;

    // Some attributes...

}

@Entity
public class B {

    @Id
    protected Long id;

    @OneToOne(mappedBy = "b")
    @MapsId
    @JoinColumn(name = "id")
    private A a;

    // Some attributes...
    
}

I used a similar solution proposed by @K.Nicholas . I just created a copy of entity B to do the temporary calculations. I did not call repositoryForB.save(b) . So when saving a only the attributes of a itself were stored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM