首页 > 解决方案 > 如何使用 Hibernate 持久化嵌套对象?

问题描述

我有两个类,Customer 和 ShoppingCart。这两个类的java结构如下:

客户等级:

@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

}

购物车类:

@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
}

如果需要,这是 User 类:

@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
}

我以这种方式配置了存储库类:

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
}

@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
}

@Repository
public interface ShoppingCartRepository extends CrudRepository<ShoppingCart, Integer> {
}

我想要的很简单,一旦我创建了一个客户,我还想在数据库中创建一个 ShoppingCart 元组。它实际上工作正常,唯一的问题是与 Customer 相关的 ShoppingCart 的外键设置为 null。我只是将 shopping_cart_id 属性设置为一个整数值(正确)。

我用来测试它的代码如下:

Customer customer = new Customer("stefanosambruna", "ste23s@hotmail.it", "*******");
customerRepository.save(customer);

现在,我可能在错误的地方放了一些注释,但我真的不知道是哪些。它与构造函数有关吗?还是 @JoinColumn 和 mappedBy 配置?我在 StackOverflow 和其他一些来源上阅读了关于这个主题的所有问答,但我没有发现任何 100% 有用的东西。希望已经提供了所有必要的细节。

标签: javaspringhibernatespring-data-jpa

解决方案


推荐阅读