我有两个班,CarRentalCompany
@Entity
public class CarRentalCompany {
private static Logger logger = Logger.getLogger(CarRentalCompany.class.getName());
@Id
private String name;
@OneToMany(cascade = CascadeType.ALL)
private List<Car> cars;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<CarType> carTypes = new ArrayList<>(); //TODO: kan betere datastructuur zijn
/***************
* CONSTRUCTOR *
***************/
public CarRentalCompany()
{
// DEFAULT CONSTRUCTOR
}
public CarRentalCompany(String name, List<Car> cars) {
logger.log(Level.INFO, "<{0}> Car Rental Company {0} starting up...", name);
setName(name);
this.cars = cars;
for(Car car:cars)
carTypes.add(car.getType());
}
...
}
和CarType
@Entity
public class CarType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private String name;
private int nbOfSeats;
private boolean smokingAllowed;
private double rentalPricePerDay;
//trunk space in liters
private float trunkSpace;
/***************
* CONSTRUCTOR *
***************/
public CarType()
{
}
public CarType(String name, int nbOfSeats, float trunkSpace, double rentalPricePerDay, boolean smokingAllowed) {
this.name = name;
this.nbOfSeats = nbOfSeats;
this.trunkSpace = trunkSpace;
this.rentalPricePerDay = rentalPricePerDay;
this.smokingAllowed = smokingAllowed;
}
运行该应用程序时,它将引发以下异常:
NucleusFatalUserException:尝试为孩子分配钥匙 带有关键字的“ CarType(6614661952700416)”父级 “ CarRentalCompany(” Hertz“)”。父键是不可变的
我该怎么做才能正确获得CarType的密钥?
答案 0 :(得分:0)
在添加CarType实体之前,您不是persisting您的CarRentalCompany实体。看到 类似线程here。持久操作必须仅用于新实体。从未与数据库行关联的实体是新实体,这意味着数据库中没有与该实体匹配的表记录。