I have an issue with one of my One-To-Many relationships. My problem is when I add a Tenant into an Apartment it doesn't set the column value in the Tenant to the ApartmentID. The thing is I have the exact same relationship with other classes and they are working fine... Does anyone have an idea why it's not wotking? Thanks
Apartment :
@Entity
public class Apartment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ApartmentID",unique = true, nullable = false)
public int apartmentID;
@OneToMany(mappedBy = "apartment", cascade = CascadeType.ALL)
private List<Tenant> tenants;
}
Tenant :
@Entity
public class Tenant {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="TenantID",unique = true, nullable = false)
public int tenantID;
@ManyToOne
@JoinColumn(name = "ApartmentID")
private Apartment apartment;
}
In your bi-directional relationship Tenant
is the owner of the relationship. Since you are persisting Apartment
you have to manually set the apartment of tenant. If you want to get rid of manual setting change your @OneToMany
as follows:
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="ApartmentID",referencedColumnName="ApartmentID")
private List<Tenant> tenants;
By the way, with your current sample if you are persisting tenant with apartment; apartment will be automatically persisted.