I'm trying to make tests of my CRUD operations in my springboot Restful Web Service, but I can't, because every tutorial I follow ends up with some error !
This time I'm publishing this in order to get some help from you.
My CloudProduct.java
package com.proj.my.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.sql.Date;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Table;
#Entity
#Table(name="cloud_product_info")
#SQLDelete(sql = "UPDATE cloud_product_info SET deleted = true WHERE product_id=?")
#Where(clause = "deleted=false")
//#FilterDef(name="", parameters = #ParamDef(name="isDeleted", type = "boolean"))
//#Filter(name="deletedBookFilter", condition = "deleted = :isDeleted")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class CloudProduct {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer productId;
private String productName;
private Float priceInEuros;
#CreationTimestamp
#Column(updatable = false, name = "created_at")
private Date createdAt;
private Boolean deleted = Boolean.FALSE;
#JsonIgnore
public Boolean getdeleted() {
return deleted;
}
#JsonIgnore
public void setdeleted(Boolean deleted) {
this.deleted = deleted;
}
public CloudProduct(Integer productId, String productName, Float priceInEuros) {
this.productId = productId;
this.productName = productName;
this.priceInEuros = priceInEuros;
}
public CloudProduct() {
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Float getpriceInEuros() {
return priceInEuros;
}
public void setProductPrice(Float priceInEuros) {
this.priceInEuros = priceInEuros;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return "Product{" +
"id=" + productId +
", name='" + productName + '\'' +
", price=" + priceInEuros +
'}';
}
}
My CloudProductController
package com.proj.my.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.model.CloudProduct;
import com.proj.my.service.CloudProductService;
#RestController
#RequestMapping("/cloudproduct")
public class CloudProductController
{
CloudProductService cloudProductService;
public CloudProductController(CloudProductService cloudProductService)
{
this.cloudProductService = cloudProductService;
}
#GetMapping("{productId}")
public CloudProduct getCloudProductDetails(#PathVariable("productId") Integer productId){
return cloudProductService.getCloudProduct(productId);
}
#GetMapping("getAll")
public List<CloudProduct> getCloudProductDetails(){
return cloudProductService.getCloudProducts();
}
#PostMapping
public String createCloudProductDetails(#RequestBody CloudProduct cloudProduct){
cloudProductService.createCloudProduct(cloudProduct);
return "Success";
}
#PutMapping
public CloudProduct updateCloudProductDetails(#RequestBody CloudProduct cloudProduct){
return cloudProductService.updateCloudProduct(cloudProduct);
}
#DeleteMapping("{productId}")
public String deleteCloudProductDetails(#PathVariable("productId")Integer productId){
cloudProductService.deleteCloudProduct(productId);
return "Deleted!";
}
}
My CloudProductServiceImpl.java
package com.proj.my.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import com.proj.my.model.CloudProduct;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
#Service
public class CloudProductServiceImpl implements CloudProductService
{
CloudProductRepository cloudProductRepository;
public CloudProductServiceImpl(CloudProductRepository cloudProductRepository) {
this.cloudProductRepository = cloudProductRepository;
}
#Override
public String createCloudProduct(CloudProduct cloudProduct){
cloudProductRepository.save(cloudProduct);
return "Success";
}
#Override
public CloudProduct updateCloudProduct(CloudProduct cloudProduct){
CloudProduct existingCloudProductDetails = getCloudProduct(cloudProduct.getProductId());
if(cloudProduct.getProductName() != null){
existingCloudProductDetails.setProductName(cloudProduct.getProductName());
}
if(cloudProduct.getpriceInEuros() != null){
existingCloudProductDetails.setProductPrice(cloudProduct.getpriceInEuros());
}
return cloudProductRepository.save(existingCloudProductDetails);
}
#Override
public CloudProduct getCloudProduct(Integer cloudProductId){
return cloudProductRepository.findById(cloudProductId).get();
}
#Override
public String deleteCloudProduct(Integer cloudProductId){
cloudProductRepository.deleteById(cloudProductId);
return "Success";
}
#Override
public List<CloudProduct> getCloudProducts()
{
return cloudProductRepository.findAll();
}
}
My CloudProductService.java
package com.proj.my.service;
import java.util.List;
import com.proj.my.model.CloudProduct;
public interface CloudProductService {
public String createCloudProduct(CloudProduct cloudProduct);
public CloudProduct updateCloudProduct(CloudProduct cloudProduct);
public String deleteCloudProduct(Integer cloudProductId);
public CloudProduct getCloudProduct(Integer cloudProductId);
public List<CloudProduct> getCloudProducts();
}
My cloudProductRepository.java
package com.proj.my.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.proj.my.model.CloudProduct;
public interface CloudProductRepository extends JpaRepository<CloudProduct, Integer> {
}
And finally, my CloudProductControllerTest.java
package com.proj.my.service.impl;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.proj.my.controller.CloudProductController;
import com.proj.my.model.CloudProduct;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
import java.util.ArrayList;
import java.util.List;
#WebMvcTest(CloudProductController.class)
public class CloudProductControllerTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private ObjectMapper objectMapper;
#MockBean
private CloudProductRepository cloudProductRepository;
#MockBean
private CloudProductService cloudProductService;
#Test
public void testgetCloudProductDetails() throws Exception{
List<CloudProduct> productList = new ArrayList<>();
productList.add(new CloudProduct(1, "Maria", (float) 232));
productList.add(new CloudProduct(2, "Maria", (float) 232));
Mockito.when(cloudProductRepository.findAll()).thenReturn(productList);
String url = "";
mockMvc.perform(get(url)).andExpect(status().isOk());
String actualJsonResponse = mvcResult.getResponse().getContentAsString();
System.out.println(actualJsonResponse);
String expectedJsonResponse = objectMapper.writeValueAsString(productList);
System.out.println(expectedJsonResponse);
assertEquals(actualJsonResponse, expectedJsonResponse);
}
}
And this test is wrong, because the expected here is "[]" and I'm getting " [{"productId":1,"productName":"Maria","priceInEuros":232.0,"createdAt":null},{"productId":2,"productName":"Maria","priceInEuros":232.0,"createdAt":null}]" which is correct... the expected is null, why ?
Related
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryService': Unsatisfied dependency expressed through field 'categoryRepository': Error creating bean with name 'categoryRepository' defined in com.example.demo.repository.CategoryRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class com.example.demo.model.Category
package com.example.demo.model;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
#Table(name="categories")
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name")
private #NotNull String categoryName;
#Column(name = "description")
private String description;
#Column(name = "image")
private String imageUrl;
public Category() {
}
public Category(#NotNull String categoryName) {
this.categoryName = categoryName;
}
public Category(#NotNull String categoryName, String description) {
this.categoryName = categoryName;
this.description = description;
}
public Category(#NotNull String categoryName, String description, String imageUrl) {
this.categoryName = categoryName;
this.description = description;
this.imageUrl = imageUrl;
}
public String getCategoryName() {
return this.categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "User {category id=" + id + ", category name='" + categoryName + "', description='" + description + "'}";
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
package com.example.demo.controllers;
import java.util.ArrayList;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.service.CategoryService;
import com.example.demo.common.ApiResponse;
import com.example.demo.model.Category;
#RestController
#RequestMapping("category")
public class CategoryController {
#Autowired
private CategoryService categoryService;
#PostMapping("")
public ResponseEntity<ApiResponse> storeCategory(#Valid #RequestBody Category category) {
categoryService.saveCategory(category);
ArrayList<String> message = new ArrayList<String>();
message.add("Category is added successfully");
return new ResponseEntity<ApiResponse>(new ApiResponse(true, message), HttpStatus.OK);
}
}
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.example.demo.model.Category;
import com.example.demo.repository.CategoryRepository;
#Service
public class CategoryService {
#Autowired
private CategoryRepository categoryRepository;
public void saveCategory(Category category) {
// categoryRepository.saveAndFlush(category);
}
}
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Category;
#Repository("categoryRepository")
public interface CategoryRepository extends JpaRepository<Category, Integer> {
Category findByCategoryName(String categoryName);
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories
#ComponentScan(basePackages = { "com.example.demo.model.*" })
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
how to solve this error?
I ran the program but it showed this error.
Try adding this tag #EnableJpaRepositories in your MainApplication class and #ComponentScan(basePackages = {
"your entities package.*"
}
I'm trying to make a few tests of my CRUD operations in my springboot Restful Web Service, but I can't, because every tutorial I follow ends up with some error !
This time I'm publishing this in order to get some help from you.
My CloudProduct.java
package com.proj.my.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.sql.Date;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Table;
#Entity
#Table(name="cloud_product_info")
#SQLDelete(sql = "UPDATE cloud_product_info SET deleted = true WHERE product_id=?")
#Where(clause = "deleted=false")
//#FilterDef(name="", parameters = #ParamDef(name="isDeleted", type = "boolean"))
//#Filter(name="deletedBookFilter", condition = "deleted = :isDeleted")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class CloudProduct {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer productId;
private String productName;
private Float priceInEuros;
#CreationTimestamp
#Column(updatable = false, name = "created_at")
private Date createdAt;
private Boolean deleted = Boolean.FALSE;
#JsonIgnore
public Boolean getdeleted() {
return deleted;
}
#JsonIgnore
public void setdeleted(Boolean deleted) {
this.deleted = deleted;
}
public CloudProduct(Integer productId, String productName, Float priceInEuros) {
this.productId = productId;
this.productName = productName;
this.priceInEuros = priceInEuros;
}
public CloudProduct() {
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Float getpriceInEuros() {
return priceInEuros;
}
public void setProductPrice(Float priceInEuros) {
this.priceInEuros = priceInEuros;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return "Product{" +
"id=" + productId +
", name='" + productName + '\'' +
", price=" + priceInEuros +
'}';
}
}
My CloudProductController
package com.proj.my.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.model.CloudProduct;
import com.proj.my.service.CloudProductService;
#RestController
#RequestMapping("/cloudproduct")
public class CloudProductController
{
CloudProductService cloudProductService;
public CloudProductController(CloudProductService cloudProductService)
{
this.cloudProductService = cloudProductService;
}
#GetMapping("{productId}")
public CloudProduct getCloudProductDetails(#PathVariable("productId") Integer productId){
return cloudProductService.getCloudProduct(productId);
}
#GetMapping("getAll")
public List<CloudProduct> getCloudProductDetails(){
return cloudProductService.getCloudProducts();
}
#PostMapping
public String createCloudProductDetails(#RequestBody CloudProduct cloudProduct){
cloudProductService.createCloudProduct(cloudProduct);
return "Success";
}
#PutMapping
public CloudProduct updateCloudProductDetails(#RequestBody CloudProduct cloudProduct){
return cloudProductService.updateCloudProduct(cloudProduct);
}
#DeleteMapping("{productId}")
public String deleteCloudProductDetails(#PathVariable("productId")Integer productId){
cloudProductService.deleteCloudProduct(productId);
return "Deleted!";
}
}
My CloudProductServiceImpl.java
package com.proj.my.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import com.proj.my.model.CloudProduct;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
#Service
public class CloudProductServiceImpl implements CloudProductService
{
CloudProductRepository cloudProductRepository;
public CloudProductServiceImpl(CloudProductRepository cloudProductRepository) {
this.cloudProductRepository = cloudProductRepository;
}
#Override
public String createCloudProduct(CloudProduct cloudProduct){
cloudProductRepository.save(cloudProduct);
return "Success";
}
#Override
public CloudProduct updateCloudProduct(CloudProduct cloudProduct){
CloudProduct existingCloudProductDetails = getCloudProduct(cloudProduct.getProductId());
if(cloudProduct.getProductName() != null){
existingCloudProductDetails.setProductName(cloudProduct.getProductName());
}
if(cloudProduct.getpriceInEuros() != null){
existingCloudProductDetails.setProductPrice(cloudProduct.getpriceInEuros());
}
return cloudProductRepository.save(existingCloudProductDetails);
}
#Override
public CloudProduct getCloudProduct(Integer cloudProductId){
return cloudProductRepository.findById(cloudProductId).get();
}
#Override
public String deleteCloudProduct(Integer cloudProductId){
cloudProductRepository.deleteById(cloudProductId);
return "Success";
}
#Override
public List<CloudProduct> getCloudProducts()
{
return cloudProductRepository.findAll();
}
}
My CloudProductService.java
package com.proj.my.service;
import java.util.List;
import com.proj.my.model.CloudProduct;
public interface CloudProductService {
public String createCloudProduct(CloudProduct cloudProduct);
public CloudProduct updateCloudProduct(CloudProduct cloudProduct);
public String deleteCloudProduct(Integer cloudProductId);
public CloudProduct getCloudProduct(Integer cloudProductId);
public List<CloudProduct> getCloudProducts();
}
My cloudProductRepository.java
package com.proj.my.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.proj.my.model.CloudProduct;
public interface CloudProductRepository extends JpaRepository<CloudProduct, Integer> {
}
And finally, my CloudProductControllerTest.java
package com.proj.my.service.impl;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.proj.my.controller.CloudProductController;
import com.proj.my.model.CloudProduct;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
import java.util.ArrayList;
import java.util.List;
#WebMvcTest(CloudProductController.class)
public class CloudProductControllerTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private ObjectMapper objectMapper;
#MockBean
private CloudProductRepository cloudProductRepository;
#MockBean
private CloudProductService cloudProductService;
#Test
public void testgetCloudProductDetails() throws Exception{
List<CloudProduct> productList = new ArrayList<>();
productList.add(new CloudProduct(1, "Maria", (float) 232));
productList.add(new CloudProduct(2, "Maria", (float) 232));
Mockito.when(cloudProductRepository.findAll()).thenReturn(productList);
String url = "";
mockMvc.perform(get(url)).andExpect(status().isOk());
String actualJsonResponse = mvcResult.getResponse().getContentAsString();
System.out.println(actualJsonResponse);
String expectedJsonResponse = objectMapper.writeValueAsString(productList);
System.out.println(expectedJsonResponse);
assertEquals(actualJsonResponse, expectedJsonResponse);
}
}
And this test is wrong, because the expected here is "[]" and I'm getting " [{"productId":1,"productName":"Maria","priceInEuros":232.0,"createdAt":null},{"productId":2,"productName":"Maria","priceInEuros":232.0,"createdAt":null}]" which is correct... the expected is null, why ?
I've done a few changes on my code, because now I want to have a soft deletion instead of a normal one.
I would only need a few JPA annotations for this purpose.
I think I got the right idea, but now I can't even run it because it give the following error:
"""Type mismatch: cannot convert from String to Class<?>"""
My CloudProduct.java ( the one with the error ) :
package com.proj.my.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.Id;
import java.sql.Date;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.Filter;
import org.hibernate.annotations.FilterDef;
import org.hibernate.annotations.ParamDef;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Table;
#Entity
#Table(name="cloud_product_info")
#SQLDelete(sql = "UPDATE cloud_products_info SET deleted = true WHERE id=?")
#FilterDef(name = "deletedProductFilter", parameters = #ParamDef(name = "isDeleted", type = "boolean"))
#Filter(name = "deletedProductFilter", condition = "deleted = :isDeleted")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class CloudProduct {
#Id
private String productId;
private String productName;
private String productPrice;
#CreationTimestamp
#Column(updatable = false, name = "created_at")
private Date createdAt;
private boolean deleted = Boolean.FALSE;
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public CloudProduct(String productId, String productName, String productPrice, Date createdAt, boolean deleted) {
this.productId = productId;
this.productName = productName;
this.productPrice = productPrice;
this.createdAt = createdAt;
this.deleted = deleted;
}
public CloudProduct() {
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
}
The error is implicit on :
#FilterDef(name = "deletedProductFilter", parameters = #ParamDef(name = "isDeleted", type = "boolean"))
Specifically on the "type = "boolean" ".
He is my CloudProductController.java
package com.proj.my.controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.proj.my.model.CloudProduct;
import com.proj.my.service.CloudProductService;
#RestController
#RequestMapping("/cloudproduct")
public class CloudProductController
{
CloudProductService cloudProductService;
public CloudProductController(CloudProductService cloudProductService)
{
this.cloudProductService = cloudProductService;
}
#GetMapping("{productId}")
public CloudProduct getCloudProductDetails(#PathVariable("productId") String productId){
return cloudProductService.getCloudProduct(productId);
}
#PostMapping
public String createCloudProductDetails(#RequestBody CloudProduct cloudProduct){
cloudProductService.createCloudProduct(cloudProduct);
return "Success";
}
#PutMapping
public String updateCloudProductDetails(#RequestBody CloudProduct cloudProduct){
cloudProductService.updateCloudProduct(cloudProduct);
return "Updated !";
}
#DeleteMapping("/{productId}")
public void removeOne(#PathVariable("productId") String productId) {
cloudProductService.remove(productId);
}
#GetMapping
public Iterable<CloudProduct> findAll(#RequestParam(value = "isDeleted", required = false, defaultValue = "false") boolean isDeleted) {
return cloudProductService.findAll(isDeleted);
}
}
My CloudProductService.java :
package com.proj.my.service;
import com.proj.my.model.CloudProduct;
public interface CloudProductService {
public String createCloudProduct(CloudProduct cloudProduct);
public String updateCloudProduct(CloudProduct cloudProduct);
public CloudProduct getCloudProduct(String cloudProductId);
public Iterable<CloudProduct> findAll(boolean isDeleted);
public void remove(String cloudProductId);
}
My CloudProductServiceimpl.java :
package com.proj.my.service.impl;
import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.proj.my.model.CloudProduct;
import com.proj.my.repository.CloudProductRepository;
import com.proj.my.service.CloudProductService;
import jakarta.persistence.EntityManager;
#Service
public class CloudProductServiceImpl implements CloudProductService
{
CloudProductRepository cloudProductRepository;
#Autowired
private EntityManager entityManager;
public CloudProductServiceImpl(CloudProductRepository cloudProductRepository) {
this.cloudProductRepository = cloudProductRepository;
}
#Override
public String createCloudProduct(CloudProduct cloudProduct){
cloudProductRepository.save(cloudProduct);
return "Success";
}
#Override
public String updateCloudProduct(CloudProduct cloudProduct){
cloudProductRepository.save(cloudProduct);
return "Success";
}
#Override
public CloudProduct getCloudProduct(String cloudProductId){
return cloudProductRepository.findById(cloudProductId).get();
}
public void remove(String cloudProductId){
cloudProductRepository.deleteById(cloudProductId);
}
public Iterable<CloudProduct> findAll(boolean isDeleted){
Session session = entityManager.unwrap(Session.class);
Filter filter = session.enableFilter("deletedProductFilter");
filter.setParameter("isDeleted", isDeleted);
Iterable<CloudProduct> products = cloudProductRepository.findAll();
session.disableFilter("deletedProductFilter");
return products;
}
}
I hope you can help me with this one, THANKS !!!
I'm trying to build an API with Spring Boot, but I keep getting an error when dealing with #OneToMany entities. The Bean seem to not be able to get an entity I'm referencing by ID through the JSON from the database and constructing it to insert into the other entity. Sounds complicated, so here's the code for everything and the error. I googled and googled and couldn't find a fitting answer to my specific situation.
Entity Turma:
package com.residencia.academia.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "turma")
public class Turma {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_turma")
private Integer idTurma;
#Column(name = "horario")
private Date horarioTurma;
#Column(name = "duracao")
private Integer duracaoTurma;
#Column(name = "data_inicio")
private Date dataInicioTurma;
#Column(name = "data_fim")
private Date dataFimTurma;
#ManyToOne
#JoinColumn(name = "id_instrutor", referencedColumnName = "id_instrutor")
private Instrutor instrutor;
public Integer getIdTurma() {
return idTurma;
}
public void setIdTurma(Integer idTurma) {
this.idTurma = idTurma;
}
public Date getHorarioTurma() {
return horarioTurma;
}
public void setHorarioTurma(Date horarioTurma) {
this.horarioTurma = horarioTurma;
}
public Integer getDuracaoTurma() {
return duracaoTurma;
}
public void setDuracaoTurma(Integer duracaoTurma) {
this.duracaoTurma = duracaoTurma;
}
public Date getDataInicioTurma() {
return dataInicioTurma;
}
public void setDataInicioTurma(Date dataInicioTurma) {
this.dataInicioTurma = dataInicioTurma;
}
public Date getDataFimTurma() {
return dataFimTurma;
}
public void setDataFimTurma(Date dataFimTurma) {
this.dataFimTurma = dataFimTurma;
}
public Instrutor getInstrutor() {
return instrutor;
}
public void setInstrutor(Instrutor instrutor) {
this.instrutor = instrutor;
}
}
Turma's Controller:
package com.residencia.academia.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.residencia.academia.entity.Turma;
import com.residencia.academia.service.TurmaService;
#RestController
#RequestMapping("/turma")
public class TurmaController {
#Autowired
private TurmaService turmaService;
#GetMapping
public ResponseEntity<List<Turma>> findAll() {
return ResponseEntity.ok().body(turmaService.findAllTurma());
}
#GetMapping("/{id}")
public ResponseEntity<Turma> findById(#PathVariable Integer id) {
return ResponseEntity.ok().body(turmaService.findByIdTurma(id));
}
#PostMapping
public Turma save(#RequestBody Turma turma) {
return turmaService.saveTurma(turma);
}
#PutMapping
public Turma update(#RequestBody Turma turma) {
return turmaService.updateTurma(turma);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id) {
turmaService.deleteTurma(id);
}
}
Turma's Service:
package com.residencia.academia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.residencia.academia.entity.Turma;
import com.residencia.academia.repository.TurmaRepository;
#Service
public class TurmaService {
#Autowired
private TurmaRepository turmaRepository;
public List<Turma> findAllTurma() {
return turmaRepository.findAll();
}
public Turma findByIdTurma(Integer id) {
return turmaRepository.findById(id).get();
}
public Turma saveTurma(Turma turma) {
return turmaRepository.save(turma);
}
public Turma updateTurma(Turma turma) {
return turmaRepository.save(turma);
}
public void deleteTurma(Integer id) {
turmaRepository.deleteById(id);
}
public void deleteTurma(Turma turma) {
turmaRepository.delete(turma);
}
}
Turma's Repository:
package com.residencia.academia.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.residencia.academia.entity.Turma;
public interface TurmaRepository extends JpaRepository<Turma, Integer> {
}
Entity Instrutor:
package com.residencia.academia.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "instrutor")
public class Instrutor {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_instrutor")
private Integer idInstrutor;
#Column(name = "rg")
private Integer rgInstrutor;
#Column(name = "nome")
private String nomeInstrutor;
#Column(name = "nascimento")
private Date dataNascimentoInstrutor;
#Column(name = "titulacao")
private Integer titulacaoInstrutor;
#OneToMany(mappedBy = "instrutor")
private List<Turma> turmaList;
public Integer getIdInstrutor() {
return idInstrutor;
}
public void setIdInstrutor(Integer idInstrutor) {
this.idInstrutor = idInstrutor;
}
public Integer getRgInstrutor() {
return rgInstrutor;
}
public void setRgInstrutor(Integer rgInstrutor) {
this.rgInstrutor = rgInstrutor;
}
public String getNomeInstrutor() {
return nomeInstrutor;
}
public void setNomeInstrutor(String nomeInstrutor) {
this.nomeInstrutor = nomeInstrutor;
}
public Date getDataNascimentoInstrutor() {
return dataNascimentoInstrutor;
}
public void setDataNascimentoInstrutor(Date dataNascimentoInstrutor) {
this.dataNascimentoInstrutor = dataNascimentoInstrutor;
}
public Integer getTitulacaoInstrutor() {
return titulacaoInstrutor;
}
public void setTitulacaoInstrutor(Integer titulacaoInstrutor) {
this.titulacaoInstrutor = titulacaoInstrutor;
}
public List<Turma> getTurmaList() {
return turmaList;
}
public void setTurmaList(List<Turma> turmaList) {
this.turmaList = turmaList;
}
}
Instrutor's Controller:
package com.residencia.academia.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.residencia.academia.entity.Instrutor;
import com.residencia.academia.service.InstrutorService;
#RestController
#RequestMapping("/instrutor")
public class InstrutorController {
#Autowired
private InstrutorService instrutorService;
#GetMapping
public ResponseEntity<List<Instrutor>> findAll() {
return ResponseEntity.ok().body(instrutorService.findAllInstrutor());
}
#GetMapping("/{id}")
public ResponseEntity<Instrutor> findById(#PathVariable Integer id) {
return ResponseEntity.ok().body(instrutorService.findByIdInstrutor(id));
}
#PostMapping
public Instrutor save(#RequestBody Instrutor instrutor) {
return instrutorService.saveInstrutor(instrutor);
}
#PutMapping
public Instrutor update(#RequestBody Instrutor instrutor) {
return instrutorService.updateInstrutor(instrutor);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Integer id) {
instrutorService.deleteInstrutor(id);
}
}
Instrutor's Service:
package com.residencia.academia.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.residencia.academia.entity.Instrutor;
import com.residencia.academia.repository.InstrutorRepository;
#Service
public class InstrutorService {
#Autowired
private InstrutorRepository instrutorRepository;
public List<Instrutor> findAllInstrutor() {
return instrutorRepository.findAll();
}
public Instrutor findByIdInstrutor(Integer id) {
return instrutorRepository.findById(id).get();
}
public Instrutor saveInstrutor(Instrutor instrutor) {
return instrutorRepository.save(instrutor);
}
public Instrutor updateInstrutor(Instrutor instrutor) {
return instrutorRepository.save(instrutor);
}
public void deleteInstrutor(Integer id) {
instrutorRepository.deleteById(id);
}
public void deleteInstrutor(Instrutor instrutor) {
instrutorRepository.delete(instrutor);
}
}
Instrutor's Repository:
package com.residencia.academia.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.residencia.academia.entity.Instrutor;
public interface InstrutorRepository extends JpaRepository<Instrutor, Integer> {
}
JSON Structure:
{
"horarioTurma": "2022-06-29T18:00:00",
"duracaoTurma": 60,
"dataInicioTurma": "2022-06-29",
"dataFimTurma": "2022-07-29",
"instrutor": 1
}
HTTP Response:
400 Bad Request
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.residencia.academia.entity.Instrutor` (although at least one Creator exists): no int/Int-argument constructor/factory method to deserialize from Number value (1)
Any help is appreciated!
im using UUID in my application as Primary Key i have problem whene find data by id give me exception error.
this is Note Class
package com.example.demo.model;
import java.util.Date;
import java.util.UUID;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
#AutoConfigurationPackage
#Entity
public class Note {
#Id
#GeneratedValue( strategy = GenerationType.AUTO,generator = "pg-uuid")
#GenericGenerator(name = "pg-uuid",strategy = "uuid2")
private UUID id;
private String title;
private String text;
#ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.MERGE)
private Notebook notebook;
private Date lastModifiedOn;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Notebook getNotebook() {
return notebook;
}
public void setNotebook(Notebook notebook) {
this.notebook = notebook;
}
public Date getLastModifiedOn() {
return lastModifiedOn;
}
public void setLastModifiedOn(Date lastModifiedOn) {
this.lastModifiedOn = lastModifiedOn;
}
this is NoteController
package com.example.demo.controller;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.MyMapper;
import com.example.demo.Repository.NoteBookRepository;
import com.example.demo.Repository.NoteRepository;
import com.example.demo.model.Note;
import com.example.demo.model.Notebook;
import com.example.demo.view.NoteViewModle;
#RestController
#RequestMapping("/api/note")
#CrossOrigin
public class NoteController {
#Autowired
NoteRepository noteRepository;
#Autowired
NoteBookRepository notebookRepository;
#Autowired
MyMapper maper;
#GetMapping("/all")
public List<NoteViewModle> getAllNote(){
List<Note> list = this.noteRepository.findAll();
List<NoteViewModle> noteViewModles = (List<NoteViewModle>) list.stream().map(note ->maper.convertToNodeViewModel(note)).collect(Collectors.toList());
return noteViewModles;
}
#GetMapping("/byId/{id}")
public NoteViewModle getNotreById(#PathVariable("id") UUID id) {
System.out.println(id);
Note note = this.noteRepository.findById(id).orElse(null);
if(note == null)
{
System.out.println("In If");
throw new EntityNotFoundException();
}
NoteViewModle modle = maper.convertToNodeViewModel(note);
return modle;
}
#GetMapping("/byNoteBook/{notebookId}")
public List<Note> getNotesByNoteBook(#PathVariable("notebookId") String id)
{
return this.noteRepository.findAllByNotebook(this.notebookRepository.findById(UUID.fromString(id)).orElse(new Notebook()));
}
#PostMapping("/add")
public Note save(#RequestBody NoteViewModle modle)
{
Note note = maper.convertToNodeEntity(modle);
return this.noteRepository.save(note);
}
#DeleteMapping("/deltebyId/{id}")
public void deleteNoteById(#PathVariable("id") String id) {
this.noteRepository.deleteById(UUID.fromString(id));
}
}
this is MyMapper to mape the json data
package com.example.demo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.demo.Repository.NoteBookRepository;
import com.example.demo.model.Note;
import com.example.demo.model.Notebook;
import com.example.demo.view.NoteViewModle;
import com.example.demo.view.NotebookViewModel;
#Component
public class MyMapper {
#Autowired
NoteBookRepository bookRepository;
public NoteViewModle convertToNodeViewModel(Note entity) {
NoteViewModle modle = new NoteViewModle();
modle.setId(entity.getId().toString());
modle.setTitle(entity.getTitle());
modle.setText(entity.getText());
modle.setNoteBookId(entity.getNotebook().getId().toString());
modle.setData(entity.getLastModifiedOn().toString());
return modle;
}
public Note convertToNodeEntity(NoteViewModle viewModle) {
Note note = new Note();
note.setTitle(viewModle.getTitle());
note.setText(viewModle.getText());
//note.setLastModifiedOn(new SimpleDateFormat("dd/MM/yyyy").parse(viewModle.getData()));
//Notebook notebook = bookRepository.findById(UUID.fromString(viewModle.getId())).orElse(new Notebook());
return note;
}
public NotebookViewModel convertToNotebookViewModel(Notebook entity)
{
NotebookViewModel viewModel = new NotebookViewModel();
viewModel.setId(entity.getId().toString());
viewModel.setName(entity.getName());
viewModel.setNumOfNote(entity.getNotes().size());
return viewModel;
}
public Notebook convertToNotebookEntity(NotebookViewModel model) {
Notebook notebook = new Notebook();
notebook.setId(UUID.fromString(model.getId()));
notebook.setName(model.getName());
return notebook;
}
}
this is repositry class
package com.example.demo.Repository;
import java.util.List;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.model.Note;
import com.example.demo.model.Notebook;
#Repository
public interface NoteRepository extends JpaRepository<Note, UUID> {
List<Note> findAllByNotebook(Notebook notebook);
}
this is error is appears org.springframework.dao.EmptyResultDataAccessException: No class com.example.demo.model.Notebook entity with id 7e83b195-eb81-4752-a6fa-a5206c9eb1c6 exists!