休眠状态不设置外键

时间:2019-12-22 21:31:40

标签: java spring hibernate

我正在尝试使用relationships保存实体。我注释了属性,但是hibernate不使用父实体的父键,它始终为0。

我的第一个实体是一个TrafficJam,看起来像这样:

@Entity
@Table(name = "traffic_jam", schema = "public", catalog = "dwh")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class TrafficJamEntity {

  @Id
  @Column(name = "traffic_jam_id")
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="traffic_jam_seq")
  @SequenceGenerator(
        name="traffic_jam_seq",
        sequenceName="traffic_jam_id_sequence",
        allocationSize=1
  )
  private long trafficJamId;

  @Basic
  @Column(name = "reading_id")
  private long reading_id;

  @OneToMany(mappedBy = "trafficJamEntity", cascade = CascadeType.PERSIST)
  @Builder.Default
  private Set<DisturbanceCourseEntity> disturbanceCourseEntitySet = new LinkedHashSet<>();
}

子实体DisturbanceCourse如下所示:

@Entity
@Table(name = "disturbance_course", schema = "public", catalog = "dwh")
@IdClass(DisturbanceCourseEntityPK.class)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DisturbanceCourseEntity {

  @Id
  @Column(name = "traffic_jam_id")
  private long trafficJamId;

  @ManyToOne
  @JoinColumn(name = "traffic_jam_id", nullable = false, insertable = false, updatable = 
  false)
  private TrafficJamEntity trafficJamEntity;
}

如果我将干扰路线对象添加到这样的交通拥堵中:

 trafficJamEntity.getDisturbanceCourseEntitySet().add(DisturbanceCourseEntity
                                            .builder()
                                            .latitude(latlong[0])
                                            .longitude(latlong[1])
                                            .orderNumber(shapeId)
                                            .build());

并尝试保存,但出现此错误:

Fail to write to Database because: A different object with the same identifier value was 
already associated with the session 
[space.rocit.trafficetl.entities.DisturbanceCourseEntity#DisturbanceCourseEntityPK(trafficJamId=0, orderNumber=1)]; nested exception is javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [space.rocit.trafficetl.entities.DisturbanceCourseEntity#DisturbanceCourseEntityPK(trafficJamId=0, orderNumber=1)]

我认为我对关系的定义是错误的,有什么建议吗?

编辑。: 这是我的DisturbanceCourseEntityPK类:

@Data
public class DisturbanceCourseEntityPK implements Serializable {
private long trafficJamId;
private int orderNumber;
}

编辑2 .: 昨天我再次尝试,发现尝试保存时已正确设置了生成的密钥。问题在于使用@OnToMany映射设置外键

1 个答案:

答案 0 :(得分:0)

代替这样的traffic_jam_id生成值表示法更改

@GeneratedValue(strategy = GenerationType.AUTO)

检查:)