gg ff
gg ff

Reputation: 519

Hibernate OneToOne relationship java.lang.NullPointerException

I'm making cart for my Spring project, I have User entity, cart and books, one user can have only one cart, so i made OneToOne relationship between user and cart, also many carts can contain many books, so i created manyToMany relationship between cart and book my code:

Book entity:

         @ManyToMany
        @JoinTable(
        name = "books_in_cart",
        joinColumns = { @JoinColumn(name = "cart_id")},
        inverseJoinColumns = { @JoinColumn(name = "book_id")}
)
private Set<Cart> inCarts = new HashSet<>();

Cart entity:

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

and User entity

@OneToOne(mappedBy = "user",cascade = CascadeType.MERGE,fetch = FetchType.EAGER,orphanRemoval =  true)
private Cart userCart = new Cart();

Code that I use to add book to user's 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";
}

I'm getting this exception :

java.lang.NullPointerException controller.libraryController.addToCart(libraryController.java:170) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Upvotes: 0

Views: 78

Answers (1)

Andronicus
Andronicus

Reputation: 26026

The mapping is definitely wrong, probably the whole model is, because it look like you don't have a joining table at all:

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

This means, that one entity has an id named cart_id in one table and book_id in the other one, which doesn't make any sense. That is why the exception is thrown.

You need to fix your model, both database and mapping. Here's a good read about it.

Upvotes: 1

Related Questions