I have two classes, Customer and ShoppingCart. The java structure of the two classes is the following:
Customer class:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Customer extends User implements Serializable {
@OneToOne(mappedBy = "owner", cascade=CascadeType.ALL)
private ShoppingCart shoppingCart;
@OneToMany(mappedBy = "customer", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Purchase> purchases;
public Customer() {
super();
}
public Customer(String username, String email, String password) {
super(username, email, password);
this.shoppingCart = new ShoppingCart();
this.purchases = new ArrayList<>();
}
getters and setters
}
ShoppingCart class:
@Entity
public class ShoppingCart implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer shoppingCartId;
@OneToOne
@JoinColumn(name = "owner_id")
private Customer owner;
@OneToMany(mappedBy = "shoppingCart")
private List<CartItem> items;
public ShoppingCart(Customer owner) {
this.owner = owner;
this.items = new ArrayList<>();
}
public ShoppingCart() {
this.items = new ArrayList<>();
}
getters and setters
}
If needed, this is the User class:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer userId;
private String username;
private String email;
private String password;
public User() {
}
public User(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
getters and setters
}
I have configured the Repositories classes in this way:
@Repository
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
}
@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}
@Repository
public interface ShoppingCartRepository extends CrudRepository<ShoppingCart, Integer> {
}
What I want is simple, once I create a Customer, I also want to create a ShoppingCart tuple inside the database. And it actually works fine, the only problem is that the foreign key of the ShoppingCart related with the Customer is set to null. I just have the shopping_cart_id attribute set to an integer value (correctly).
The code I used to test it is the following:
Customer customer = new Customer("stefanosambruna", "ste23s@hotmail.it", "*******");
customerRepository.save(customer);
Now, I may have put some annotations in the wrong places, but I really don't know which ones. Is it related to the constructors? Or to the @JoinColumn and mappedBy configurations? I read all the Q&As about this topic here on StackOverflow and on some other sources, but I didn't find anything 100% useful. Hope to have given all the necessary details.