AirportTranslatedModel

AirportTranslatedModel

这是我的代码。我想基于父类生成一个自动ID。我正在使用一种方法来创建Airport,所以它附带的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

最佳答案

您当前的设置具有通过Long映射的AirportTranslatedModel airport_id字段-您将需要手动设置airportId才能在数据库中设置id。这可能需要您在建立AirportModel-> AirportTranslatedModel关联之前,持久保留AirportModel并可能刷新以分配其PK并使其可用,以便随后可以设置AirportTranslatedModel.airportId。

尽管JPA 2允许派生ID。如果要从AirportModel分配AirportTranslatedModel的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;
}


请注意,如果您只是将AirportTranslatedModelKey用作pk类,则无需使其可嵌入。还要注意,AirportTranslatedModelKey包含一个long airportModel-它必须与AirportModel中pk的类型以及AirportTranslatedModel中的关系属性的名称匹配。

这将允许AirportTranslatedModel从AirportModel提取出airport_id值并将其用作其PK,即使在两个实体都是新实体时可能尚未生成该值。

09-27 17:07