Here is my database structure:
When I make a REST call to user_product with an intent to update the product value I keep on getting a null pointed exception. My assumption is that the problem lies in ServiceImpl though no matter what I change the error still consists.
My serviceImpl:
x
public void update(UserProductVO userProductVO) {
UserProduct userProduct = new UserProduct();
userProduct.setId(new UserProductId(userProductVO.getProduct().getId(), userProductVO.getUser().getId()));
userProduct.setUser(userProductVO.getUser());
userProduct.setProduct(userProductVO.getProduct());
UpdatedProduct updatedProduct = new UpdatedProduct(userProductVO.getAmountOfNewProducts());
updatedProductRepository.save(updatedProduct);
userProduct.getUpdatedProducts().add(updatedProduct);
userProductRepository.save(userProduct);
Product product = productRepository.getById(userProductVO.getProduct().getId());
product.setAmount(product.getAmount() + userProductVO.getAmountOfNewProducts());
productRepository.save(product);
}
Eror log says that the problem is here:
userProduct.getUpdatedProducts().add(updatedProduct)
I would appreciate any kind of clue where I might be messing up. Thanks in advance.
Edit:
My UserProduct class:
@Entity
@Table(name = "user_product")
public class UserProduct {
@EmbeddedId
private UserProductId id;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("userId")
@JsonBackReference(value = "userJ")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@MapsId("productId")
@JsonBackReference(value = "productJ")
private Product product;
@OneToMany(
mappedBy = "userProduct",
cascade = CascadeType.ALL,
orphanRemoval = true
)
@JsonManagedReference(value = "userProductJ")
private List<UpdatedProduct> updatedProducts;
public UserProduct() {
}
public UserProduct(UserProduct user, UserProduct product, int amountOfNewProducts) {
}
public UserProduct(User user, Product product, List<UpdatedProduct> updatedProducts) {
this.user = user;
this.product = product;
this.updatedProducts = updatedProducts;
}
..getters/setters/hashcode/equals
Edit2:
My UpdatedProduct class:
@Entity
@Table(name = "updated_product")
public class UpdatedProduct {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "amount_of_new_products")
private int amountOfNewProducts;
@Column(name = "updated_on")
private Date updatedOn = new Date();
@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference(value = "userProductJ")
private UserProduct userProduct;
public UpdatedProduct() {
}
public UpdatedProduct(int amountOfNewProducts) {
this.amountOfNewProducts = amountOfNewProducts;
}
Advertisement
Answer
You would have to initialize the UserProduct
class with an empty list, not null
:
public class UserProduct {
private List<UpdatedProduct> updatedProducts = new ArrayList<>();
// rest of the fields
}
All the annotations were omitted for brevity.