![](/img/trans.png)
[英]Why can't I save my @Entity User with it's UserRepository in Spring Boot
[英]I can not save entity (Spring Boot Application)
@Entity(name = "cities")
public class City {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(length = 256, unique = true, nullable = false)
private String name;
@Column(length = 4, nullable = false, unique = true)
private String code;
// @OneToMany(mappedBy="city")
@OneToMany(cascade = CascadeType.ALL , orphanRemoval = true)
@JoinColumn(name = "city_id")
private List<ParkingFacility> parkingFacilities = new ArrayList<>();
@OneToMany(mappedBy="city")
private List<Vehicle> vehicles = new ArrayList<>();
@Entity(name = "parking_facilities")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class ParkingFacility {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Integer id;
@Column(length = 256, unique = true, nullable = false)
protected String name;
protected Integer capacity = 0;
@Column(name = "available_capacity")
protected Integer availableCapacity = 0;
// @ManyToOne(cascade=CascadeType.ALL)
// @JoinColumn(name="city_id", nullable=false)
@ManyToOne(fetch = FetchType.EAGER)
protected City city;
@OneToMany(mappedBy="parkingFacility")
private List<Vehicle> vehicles;
public class ParkingFacilityDto {
protected Integer id;
@NotBlank @Length(max = 256)
protected String name;
@Min(0)
protected Integer capacity;
@Min(0)
protected Integer availableCapacity;
@NotBlank @Length(max = 256)
protected String city;
public class ParkingFacilityMapper {
public static ParkingFacility toFacility(ParkingFacilityDto facilityDto) {
return ParkingFacility.builder()
.name(facilityDto.getName())
.capacity(facilityDto.getCapacity())
.availableCapacity(facilityDto.getAvailableCapacity())
.city(new City(InputFormatter.formatCityName(facilityDto.getCity())))
.build();
}
}
我正在嘗試為給定城市保存停車設施,但出現此錯誤:
org.hibernate.TransientPropertyValueException: object references an unsaved transient
instance - save the transient instance before flushing :
com.goosfraba.city_parking.parking_facilities.model.ParkingFacility.city ->
com.goosfraba.city_parking.cities.model.City; nested exception is
java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object
references an unsaved transient instance - save the transient instance before flushing :
com.goosfraba.city_parking.parking_facilities.model.ParkingFacility.city -> com.goosfraba.city_parking.cities.model.City",
我看到很多人建議在 StackOverflow 上提出的類似問題上使用 CascadeType.All,但如您所見,我已經在使用它,但仍然出現此錯誤。
請幫助我,因為我不知道從這里要做什么
將cascade = CascadeType.ALL
添加到:
@ManyToOne(fetch = FetchType.EAGER)
protected City city
這將解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.