java - 如何使用 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% 有用的东西。希望已经提供了所有必要的细节。
解决方案
推荐阅读
- javascript - 有没有办法在每个 onClick 事件做出反应后刷新状态?
- c++ - 在编译时检查静态函数是否存在
- python - 如何从 Flask/jinja2 循环中的列表中删除元素?
- python - 需要基于时间和基于大小的 python 文件轮换的 Concurrent_log_handler
- reactjs - 我在哪里可以添加表单字段,以便它们可以在请求有效负载中发送 POST 方法,我在 React 应用程序中并使用 Fetches
- python - 如何在python中迭代和匹配IP与IP范围(cidr)?
- flutter - 如何在颤动中调用加载方法?
- python - Ambari Agent Distro/Conf 选择版本
- azure-cosmosdb - SQL Azure 表是否类似于 Azure Cosmos DB 容器?
- java - java.io.FileNotFoundException:
/document.xml(参数不正确)