@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();
}
}
I am trying to save a Parking Facility for a given city, but I get this error:
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",
I have seen many people recommending to use CascadeType.All on similar questions asked on StackOverflow, but as you can see I am already using it, and still get this error.
Please help me as I do not know what to from here
Add cascade = CascadeType.ALL
to:
@ManyToOne(fetch = FetchType.EAGER)
protected City city
this will solve your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.