Answer the question
In order to leave comments, you need to log in
Why is null displayed instead of id in OneToMany & ManyToOne and how to fix it?
Good day!
I'm dealing with a pressing issue.
There are 2 entities:
@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 |
+---------------------+-------+-------------------------------+
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 | |
+---------------------+-------+-------------------------------+--+
Answer the question
In order to leave comments, you need to log in
So far, I decided in the following way:
Added a setter to HbDestination
public void setZones(List<Zone> zones) {
zones.forEach(zone -> zone.setDestination(this));
this.zones = zones;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question