I have a User object with a list of CardInformation objects (their payment options). If I create a new user and new CardInformation at the same time - the foreign key referencing the User database id is null (which makes sense as I haven't persisted the object). I was under the impression spring or hibernate handles this for you when saving the User object. If not - how is this solved? By setting the User model reference in the CardInformation object?
I have kept the models simple and removed most the data to easily see the onetomany relationship details.
CardInformation in database has foreign key owner_id - referencing user_id column.
These are my models - User:
@Entity
@Table(name = "User")
public class UserPersistenceModel {
/** Table id reference. */
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long id;
/** First name. */
@Column(name = "first_name")
private String firstName;
/** Email. */
@Column(name = "email", unique = true, nullable = false)
private String email;
/** List of users payment options. */
@OneToMany(mappedBy = "userPersistenceModel", cascade =
CascadeType.ALL, fetch = FetchType.LAZY)
private List<CardInformationPersistenceModel> cardInformationPersistenceModels;
Plus all getters/setters.
CardInformation model:
@Entity
@Table(name = "CardInformation")
public class CardInformationPersistenceModel {
/** Unique db id. */
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "card_id")
private Long id;
/** Card Holder Full Name. */
@Column(name = "CardHolderName")
private String cardHolderName;
/**
* Many-1 reference to owner model.
*/
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id", nullable = false)
private UserPersistenceModel userPersistenceModel;
Plus all getters/setters etc.
The error I receive is - owner_id is null when saving user object