title: Hibernate OneToOne relationship java.lang.NullPointerException
body: <p>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: </p>
  
  <p>Book entity: </p>
  
  <pre><code>         @ManyToMany
          @JoinTable(
          name = "books_in_cart",
          joinColumns = { @JoinColumn(name = "cart_id")},
          inverseJoinColumns = { @JoinColumn(name = "book_id")}
  )
  private Set&lt;Cart&gt; inCarts = new HashSet&lt;&gt;();
  </code></pre>
  
  <p>Cart entity: </p>
  
  <pre><code>@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&lt;Book&gt; books = new HashSet&lt;&gt;();
  
  public int getId() {
      return id;
  }
  
  public void setId(int id) {
      this.id = id;
  }
  
  public Set&lt;Book&gt; getBooks() {
      return books;
  }
  
  public void setBooks(Set&lt;Book&gt; books) {
      this.books = books;
  }
  }
  </code></pre>
  
  <p>and User entity</p>
  
  <pre><code>@OneToOne(mappedBy = "user",cascade = CascadeType.MERGE,fetch = FetchType.EAGER,orphanRemoval =  true)
  private Cart userCart = new Cart();
  </code></pre>
  
  <p>Code that I use to add book to user's cart: </p>
  
  <pre><code>@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";
  }
  </code></pre>
  
  <p>I'm getting this exception : </p>
  
  <blockquote>
    <p>java.lang.NullPointerException
        controller.libraryController.addToCart(libraryController.java:170)
        sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)</p>
  </blockquote>