title: When do we need to .save() an entity in Spring?
body: <p>In a relatively large Spring Boot project, I have a method with the following (overly simplified) sequence of events:</p>
  
  <pre class="lang-java prettyprint-override"><code>Car car = carRepository.save(new Car());
  Person person = personRepository.save(new Person(car)); // Car is a field of Person
  
  Engine engine = engineRepository.save(new Engine());
  person.getCar().setEngine(engine);
  
  carRepository.save(person.getCar()); // without this the engine and car relation is not registered
  </code></pre>
  
  <p><code>Car</code>, <code>Person</code> and <code>Engine</code> are all <code>@Entity</code> classes (database objects). For this example, their implementation could be the following:</p>
  
  <pre class="lang-java prettyprint-override"><code>// Car.java
  @Entity
  @Table(name = "car_tbl")
  public class Car {
      @Id
      @GeneratedValue
      @Column(name = "car_id")
      private Long id;
  
      @OneToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "engine_id", unique = true)
      private Engine engine;
  }
  
  // Person.java
  @Entity
  @Table(name = "person_tbl")
  public class Person {
      @Id
      @GeneratedValue
      @Column(name = "person_id")
      private Long id;
  
      @OneToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "car_id", nullable = false, unique = true)
      private Car car;
  }
  
  // Engine.java
  @Entity
  @Table(name = "engine_tbl")
  public class Engine {
      @Id
      @GeneratedValue
      @Column(name = "engine_id")
      private Long id;
  }
  </code></pre>
  
  <p>The above method is only used from inside a REST API method. <strong>And OSIV (Open Session In View) is enabled in the configuration properties.</strong></p>
  
  <p>The question is, why do I need to save the <code>person.getCar()</code> object? It is the same <code>Car</code> object which I just created during the same request processing. At which point does it become <em>transient</em> and not <em>managed</em> by the persistence context? I thought all changes would be flushed automatically, because OSIV is enabled.</p>
  
  <p>How can I detect cases like these and <strong>know exactly</strong> when to use the <code>.save()</code> method and when can I ignore it?</p>