Why do I get a “duplicate key value violates unique constraint” when re-using a fetched set a Hibernate managed object?

I’m using Hibernate 6.2.5.Final with an entity like this:

@Entity
@Table(name = "sen_sensor_group")
public class SensorGroup implements Serializable {
  @Id
  @Column(name = "id")
  @GenericGenerator(
      name = "sen_sensor_group_id_seq",
      strategy = "enhanced-sequence",
      parameters = {
          @Parameter(name = "sequence_name", value = "sen_sensor_group_id_seq"),
          @Parameter(name = "optimizer", value = "pooled-lo"),
          @Parameter(name = "increment_size", value = "50")})
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sen_sensor_group_id_seq")
  private Long id;

  @ManyToMany(fetch = FetchType.EAGER)
  @JoinTable(
      name = "sen_sensor_group_sensor",
      joinColumns = @JoinColumn(name = "sensor_group_id", nullable = false),
      inverseJoinColumns = @JoinColumn(name = "sensor_id", nullable = false)
  )
  @OrderBy("name")
  private Set<Sensor> sensors = new LinkedHashSet<>();

  // Other fields...
}

When updating the group, I get a “duplicate key value violates unique constraint” error if I reuse the set in the group when some of the items added already are part of the group. It seems like Hibernate is trying to re-insert items that had already existed in the set.

However, if I use a new set and add the already existing items the group persists correctly. Why does re-using the set cause existing items to be inserted?

For example, this does not work:

  @Transactional
  public SensorGroup updateSensorGroup(String username, SensorGroup sensorGroup) {
    var updatedSensorGroup = getSensorGroup(username, sensorGroup.getSensorGroupId());
    updatedSensorGroup.setName(sensorGroup.getName());

    // Clearing the set, then re-adding items causes constraint violation if items added
    // were already in the set previously.
    updatedSensorGroup.getSensors().clear();
    for (var sensor :sensorGroup.getSensors()) {
      var fetchedSensor = getSensor(username, sensor.getSensorId());
      updatedSensorGroup.getSensors().add(fetchedSensor);
    }

    return updatedSensorGroup;
  }

This does work as expected without error:

  @Transactional
  public SensorGroup updateSensorGroup(String username, SensorGroup sensorGroup) {
    var updatedSensorGroup = getSensorGroup(username, sensorGroup.getSensorGroupId());
    updatedSensorGroup.setName(sensorGroup.getName());

    // Using a new set and replacing the original works
    Set<Sensor> sensorsToKeep = new HashSet<>();
    for (var sensor : sensorGroup.getSensors()) {
      var fetchedSensor = getSensor(username, sensor.getSensorId());
      sensorsToKeep.add(fetchedSensor);
    }
    updatedSensorGroup.setSensors(sensorsToKeep);

    return updatedSensorGroup;
  }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật