如何使用Hibernate持久化嵌套对象?

时间:2018-10-18 13:07:39

标签: java spring hibernate spring-data-jpa

我有两个班级,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
}

我已经以这种方式配置了Repositories类:

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

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

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

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

我用来测试的代码如下:

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

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

0 个答案:

没有答案