![](/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.