gpt4 book ai didi

java - Hibernate OneToOne 关系 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-02 10:10:14 25 4
gpt4 key购买 nike

我正在为我的Spring项目制作购物车,我有用户实体,购物车和书籍,一个用户只能拥有一个购物车,所以我在用户和购物车之间建立了OneToOne关系,而且许多购物车可以包含许多书籍,所以我在购物车和预订之间创建了多对多关系我的代码:

图书实体:

         @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(Native Method)

最佳答案

映射肯定是错误的,可能整个模型都是错误的,因为它看起来根本没有连接表:

joinColumns = { @JoinColumn(name = "cart_id")},
inverseJoinColumns = { @JoinColumn(name = "book_id")}

这意味着,一个实体在一个表中具有名为 cart_id 的 ID,在另一个表中具有名为 book_id 的 ID,这没有任何意义。这就是抛出异常的原因。

您需要修复您的模型,包括数据库和映射。 Here's值得一读。

关于java - Hibernate OneToOne 关系 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55052412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com