Reputation: 1500
I have two entites mapped bidirectionally @OneToMany (I guess this is the right way to do so):
@Entity
@Table(name="entry")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Entry {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(unique=true)
private String name;
@OneToMany(mappedBy = "entry", fetch=FetchType.EAGER)
@JsonManagedReference
// @JsonIdentityReference(alwaysAsId=true)
private List<Address> addresses = new ArrayList<>();
.....
}
@Entity
@Table(name="address")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Null
private String line1;
@Null
private String line2;
@ManyToOne
@JoinColumn(name = "entry_id")
@JsonBackReference
private Entry entry;
....
}
When I debug the object (Entry
) just before it's sent to be saved, I can see that it contains an array (ArrayList
type) of Address
es. However, each (at this moment, the only) element of that address list contains Entry
as its attribute, and so on - they are infinitely nested.
Note: In this situation Entry
still does not have an id
assigned. So I tried first to persist(entry)
and then do address.add(entry)
, and finally flush()
. That didn't help in regards to what is said below to be the real problem.
My questions is: Is this normal?
I'm asking because when I save the Entry
object, only the parent (Entry
) record is created, and Address
is not. I even suspected that there is no way for Address
to be saved so I went ahead and created a repository interface for it. That didn't help either.
Upvotes: 0
Views: 32
Reputation: 1500
I just found out what the problem was. I started with cascade = CascadeType.ALL
option in my Entry
entity but removed it later and forgot to put it back. I didn't even know that was what saving the child object depends on. So, lesson learned, I hope someone else finds this helpful.
Upvotes: 2