我正在为Spring项目制作购物车,我有用户实体,购物车和书籍,一个用户只能有一个购物车,所以我在用户和购物车之间建立了一个OneToOne关系,很多购物车可以包含许多书籍,所以我在购物车和预订我的代码之间创建了manyToMany关系:
图书实体:
@ManyToMany
@JoinTable(
name = "books_in_cart",
joinColumns = { @JoinColumn(name = "cart_id")},
inverseJoinColumns = { @JoinColumn(name = "book_id")}
)
private Set<Cart> inCarts = new HashSet<>();
购物车实体:
@Entity
public class Cart {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "idUsers")
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@ManyToMany
@JoinTable(
name = "books_in_cart",
joinColumns = { @JoinColumn(name = "book_id")},
inverseJoinColumns = { @JoinColumn(name = "cart_id")}
)
private Set<Book> books = new HashSet<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
}
和用户实体
@OneToOne(mappedBy = "user",cascade = CascadeType.MERGE,fetch = FetchType.EAGER,orphanRemoval = true)
private Cart userCart = new Cart();
我用来将书添加到用户购物车中的代码:
@PostMapping(value = "/addToCart")
@Secured("USER")
public String addToCart(@RequestParam(name = "ids") int id,Principal principal){
System.out.println(principal.getName());
User login = userDao.getByLogin(principal.getName());
Book book = service.getById(id);
login.getUserCart().setUser(login);
login.getUserCart().getBooks().add(book);
userDao.save(login);
return "redirect:/books";
}
我遇到此异常:
java.lang.NullPointerException controller.libraryController.addToCart(libraryController.java:170) sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)
答案 0 :(得分:1)
映射肯定是错误的,可能是整个模型,因为看起来好像根本没有连接表:
joinColumns = { @JoinColumn(name = "cart_id")},
inverseJoinColumns = { @JoinColumn(name = "book_id")}
这意味着,一个实体在一个表中有一个名为cart_id
的ID,而在另一个表中有一个book_id
的ID,这没有任何意义。这就是引发异常的原因。
您需要修复模型,包括数据库和映射。 Here's很好的阅读。