Доброго времени суток!
Разбираюсь с насущной проблемой.
Имеются 2 сущности:
@Data
@Entity
@Table(name = "hb_destinations")
public class HbDestination {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "hb_destination_id", unique = true, nullable = false)
private long hbDestinationId;
private String name;
@OneToMany(mappedBy = "destination", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Zone> zones = new ArrayList<>();
}
@Data
@Entity
@Table(name = "hb_destination_zones")
public class Zone {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long destinationZoneId;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
/*@JoinColumn(name = "hb_destination_id",referencedColumnName="hb_destination_id")*/
private HbDestination destination;
}
А вот, сам код для добавления данных
HbDestination hbDestination = new HbDestination();
hbDestination.setName(name);
hbDestination.setZones(zones);
/*hbDestination.getZones.addAll(zones);*/
hbDestinationRepository.save(hbDestination);
В результате:
+---------------------+-------+-------------------------------+
| destination_zone_id | name | destination_hb_destination_id |
+---------------------+-------+-------------------------------+
| 1 | text1 | null |
| 2 | text2 | null |
| 3 | text3 | null |
+---------------------+-------+-------------------------------+
Нашел вот, такое решение -
https://stackoverflow.com/questions/9650453/hibern...
HbDestination hbDestination = new HbDestination();
Zone zone = new Zone
zone.setDestination(hbDestination);
zones.add(zone);
hbDestination.setZones(zones);
hbDestinationRepository.save(hbDestination);
В результате:
+---------------------+-------+-------------------------------+--+
| destination_zone_id | name | destination_hb_destination_id | |
+---------------------+-------+-------------------------------+--+
| 1 | null | 5 | |
| 2 | text2 | null | |
| 3 | null | 6 | |
| 4 | text3 | null | |
+---------------------+-------+-------------------------------+--+
Как корректно сохранить List со стороны HbDestination? Могу разве, что взять список zones итерировать по нему и для каждый элемент внутри сохранить.