![](/img/trans.png)
[英]In Spring Data JPA, how to create and persist inner Entity by calling a method on an instance of outer Entity
[英]How to persist an entity in Spring Data JPA without getting associated objects
假設我有2個實體
@Entity
@Table(name = "users")
public class User implements Serializable {
private User() {
}
... other fields omitted ...
@OneToMany(mappedBy = "user")
private List<Car> cars;
}
和
@Entity
@Table(name = "cars")
public class Car implements Serializable {
public Car() {
}
... Other fields omitted ...
@Column(name = "id")
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@JsonIgnore
@JoinColumn(name = "user_id")
@ManyToOne
private User user;
}
現在,每當我在CarRepository上調用save時,它都要求我在用戶字段上有一個User對象。 這樣,我仍然需要像我的UserRepository中那樣調用findById方法
...
car.setUser(userRepository.findById(userId));
carRepository.save(car);
...
Spring Data JPA是否有一種方法可以僅使用userId進行保存,而在持久保存car對象之前我不必獲取用戶對象?
您可以嘗試創建User
對象並在其中設置userId
並將其設置在car
對象中。
User existingUser = new User();
existingUser.setId(userId);
car.setUser(existingUser);
carRepository.save(car);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.