这是我的代码。我想基于父类生成一个自动ID。我正在使用一种方法来创建机场,所以我的ID就是空值。将生成AirportModel中的ID,但我不知道如何在子类中创建它。
@Entity(name = "Airport")
@Table(name = "ai_airport")
public class AirportModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "airport_id")
private List<AirportTranslatedModel> translations;
第二课(孩子):
@Entity(name = "AirportTranslated")
@IdClass(AirportTranslatedModelKey.class)
@Table(name = "ai_translated_airport")
public class AirportTranslatedModel
@Id
@Column(name="airport_id")
private Long airportId;
@Id
@Column(name="language_code", length=2)
private String languageCode;
第三个(键):
@Embeddable
public class AirportTranslatedModelKey implements Serializable {
@Column(name="airport_id")
private Long airportId;
@Column(name="language_code", length=2)
private String languageCode;
我仍然有同样的错误;日志:
Hibernate: insert into ai_airport (active, airport_code, city_code, country_code, externa
l_id, is_default, latitude, longitude, market_code, min_connection_time_DD, min_connection_time_DI, min_connection_time_id, min_connection_time_II, time_diff, VERSION) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into ai_translated_airport (airport_long_name, airport_short_name, airp
ort_id, language_code) values (?, ?, ?, ?)
ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Column 'airport_id' cannot be null
答案 0 :(得分:1)
您当前的设置具有通过Long映射的AirportTranslatedModel airport_id字段 - 您需要手动设置airportId以使其在数据库中设置ID。这可能需要您持久保存AirportModel并可能在建立AirportModel-&gt; AirportTranslatedModel关联之前刷新其PK并且可用,以便您可以设置AirportTranslatedModel.airportId。
JPA 2虽然允许派生的ID。如果您希望AirportTranslatedModel从AirportModel分配其ID,则需要与它建立关系。 http://wiki.eclipse.org/EclipseLink/Examples/JPA/2.0/DerivedIdentifiers
有一个简单的例子如果您要以类似的方式为类建模,它可能看起来像:
public class AirportModel {
..
@OneToMany(mappedby="airportModel", cascade = CascadeType.ALL, orphanRemoval = true)
private List<AirportTranslatedModel> translations;
..
}
public class AirportTranslatedModel {
@Id
@JoinColumn(name="airport_id")
private AirportModel airportModel;
@Id
@Column(name="language_code", length=2)
private String languageCode;
..
}
public class AirportTranslatedModelKey implements Serializable {
private Long airportModel;
private String languageCode;
}
请注意,如果您只是将它用作pk类,则无需制作AirportTranslatedModelKey并可嵌入。另请注意,AirportTranslatedModelKey包含Long airportModel - 这必须与AirportModel中的pk类型以及AirportTranslatedModel中的relationship属性的名称相匹配。
这将允许AirportTranslatedModel从AirportModel中提取airport_id值并将其用作PK,即使它们可能尚未生成,但两个实体仍然是新的。