In a relatively large Spring Boot project, I have a method with the following (overly simplified) sequence of events:
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
Car
, Person
and Engine
are all @Entity
classes (database objects). For this example, their implementation could be the following:
// 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;
}
The above method is only used from inside a REST API method. And OSIV (Open Session In View) is enabled in the configuration properties.
The question is, why do I need to save the person.getCar()
object? It is the same Car
object which I just created during the same request processing. At which point does it become transient and not managed by the persistence context? I thought all changes would be flushed automatically, because OSIV is enabled.
How can I detect cases like these and know exactly when to use the .save()
method and when can I ignore it?