title: Hibernate attach and detach entity
body: <p>I have 2 entity classes
  For ex,</p>
  <pre class="lang-java prettyprint-override"><code>@Entity
  @Table(name = &quot;AAA&quot;)
  public Class AAA {
  
      @ManyToOne(optional = false, cascade = {CascadeType.ALL})
      @JoinColumn(name = &quot;bbb_id&quot;, nullable = false)
      @Valid
      BBB bbb;
  } 
  </code></pre>
  <pre class="lang-java prettyprint-override"><code>@Entity
  @Table(name = &quot;BBB&quot;)
  public Class BBB {
       @Id
       @Column(name = &quot;id&quot;)
       @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = &quot;bbb_seq_generator&quot;) 
       @SequenceGenerator(sequenceName = &quot;bbb_seq&quot;, name = &quot;bbb_seq_generator&quot;, allocationSize = 1)
       Long id;
  }     
  </code></pre>
  <p>I have a service which gets input request body as below json</p>
  <pre class="lang-java prettyprint-override"><code>&quot;aaa&quot; : 
  {
  &quot;bbb&quot; : { &quot;id&quot; : 123}
  }
  </code></pre>
  <p>I now use</p>
  <pre class="lang-java prettyprint-override"><code>aaaRepository.save(aaaObj);
  </code></pre>
  <p>to save both <code>aaa</code> and <code>bbb</code></p>
  <p>I want <code>bbb</code> to be saved only when its id value is not found in the DB (<code>findById(id)</code> gives <code>Optional.empty</code>) and retain the value if already found and just save <code>aaa</code> alone in that case.</p>
  <p>Entity <code>AAA</code> has to be persisted and entity <code>BBB</code> also to be persisted if id is null in the request body and in case if id is already present then it has to be retained the same and <code>AAA</code> has to be persisted with whatever value comes in the request body</p>
  <p>I tried but when i try to set <code>bbb</code> explicitly to <code>aaa</code>, I get detached entity exception. For the case when id is already present in request.
  I can't be without setting the id as the service layer has to know which id it should check for in the DB.</p>