I created spring boot project where I am making rest application. I have used My SQL database and I am using spring data. There is one method which adds orders based on customer id. So I am not able to figure out it will work based on spring data query or custom query and how it will be?
I have attached required codes only,
Customer.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "customers")
#NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "cust_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int custIDPK;
#Column(name = "billing_city")
private String billingCity;
#Column(name = "billing_country")
private String billingCountry;
#Column(name = "billing_state")
private String billingState;
#Column(name = "billing_street")
private String billingStreet;
#Column(name = "billing_zip")
private String billingZip;
private String company;
#Column(name = "display_name")
private String displayName;
private String email;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "other_details")
private String otherDetails;
#Column(name = "print_on_check_as")
private String printOnCheckAs;
#Column(name = "shipping_city")
private String shippingCity;
#Column(name = "shipping_country")
private String shippingCountry;
#Column(name = "shipping_state")
private String shippingState;
#Column(name = "shipping_street")
private String shippingStreet;
#Column(name = "shipping_zip")
private String shippingZip;
private String suffix;
private String title;
// bi-directional many-to-one association to Order
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private List<Order> orders;
public Customer() {
}
public int getCustIDPK() {
return this.custIDPK;
}
public void setCustIDPK(int cust_ID_PK) {
this.custIDPK = cust_ID_PK;
}
public String getBillingCity() {
return this.billingCity;
}
public void setBillingCity(String billingCity) {
this.billingCity = billingCity;
}
public String getBillingCountry() {
return this.billingCountry;
}
public void setBillingCountry(String billingCountry) {
this.billingCountry = billingCountry;
}
public String getBillingState() {
return this.billingState;
}
public void setBillingState(String billingState) {
this.billingState = billingState;
}
public String getBillingStreet() {
return this.billingStreet;
}
public void setBillingStreet(String billingStreet) {
this.billingStreet = billingStreet;
}
public String getBillingZip() {
return this.billingZip;
}
public void setBillingZip(String billingZip) {
this.billingZip = billingZip;
}
public String getCompany() {
return this.company;
}
public void setCompany(String company) {
this.company = company;
}
public String getDisplayName() {
return this.displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getOtherDetails() {
return this.otherDetails;
}
public void setOtherDetails(String otherDetails) {
this.otherDetails = otherDetails;
}
public String getPrintOnCheckAs() {
return this.printOnCheckAs;
}
public void setPrintOnCheckAs(String printOnCheckAs) {
this.printOnCheckAs = printOnCheckAs;
}
public String getShippingCity() {
return this.shippingCity;
}
public void setShippingCity(String shippingCity) {
this.shippingCity = shippingCity;
}
public String getShippingCountry() {
return this.shippingCountry;
}
public void setShippingCountry(String shippingCountry) {
this.shippingCountry = shippingCountry;
}
public String getShippingState() {
return this.shippingState;
}
public void setShippingState(String shippingState) {
this.shippingState = shippingState;
}
public String getShippingStreet() {
return this.shippingStreet;
}
public void setShippingStreet(String shippingStreet) {
this.shippingStreet = shippingStreet;
}
public String getShippingZip() {
return this.shippingZip;
}
public void setShippingZip(String shippingZip) {
this.shippingZip = shippingZip;
}
public String getSuffix() {
return this.suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Order> getOrders() {
return this.orders;
}
public void setOrders(List<Order> orders) {
this.orders = orders;
}
public Order addOrder(Order order) {
getOrders().add(order);
order.setCustomer(this);
return order;
}
public Order removeOrder(Order order) {
getOrders().remove(order);
order.setCustomer(null);
return order;
}
}
Order.java
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.util.List;
#Entity
#Table(name = "orders")
#NamedQuery(name = "Order.findAll", query = "SELECT o FROM Order o")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "order_ID_PK")
#GeneratedValue(strategy = GenerationType.AUTO)
private int order_ID_PK;
#Column(name = "custom_message")
private String customMessage;
#Temporal(TemporalType.DATE)
#Column(name = "delivery_due_date")
private Date deliveryDueDate;
#Temporal(TemporalType.DATE)
#Column(name = "invoice_creation_date")
private Date invoiceCreationDate;
#Temporal(TemporalType.DATE)
#Column(name = "payment_due_date")
private Date paymentDueDate;
// bi-directional many-to-one association to Customer
#ManyToOne
#JoinColumn(name = "cust_ID_FK")
private Customer customer;
// bi-directional many-to-many association to Product
#ManyToMany(mappedBy = "orders")
private List<Product> products;
public Order() {
}
public int getOrder_ID_PK() {
return this.order_ID_PK;
}
public void setOrder_ID_PK(int order_ID_PK) {
this.order_ID_PK = order_ID_PK;
}
public String getCustomMessage() {
return this.customMessage;
}
public void setCustomMessage(String customMessage) {
this.customMessage = customMessage;
}
public Date getDeliveryDueDate() {
return this.deliveryDueDate;
}
public void setDeliveryDueDate(Date deliveryDueDate) {
this.deliveryDueDate = deliveryDueDate;
}
public Date getInvoiceCreationDate() {
return this.invoiceCreationDate;
}
public void setInvoiceCreationDate(Date invoiceCreationDate) {
this.invoiceCreationDate = invoiceCreationDate;
}
public Date getPaymentDueDate() {
return this.paymentDueDate;
}
public void setPaymentDueDate(Date paymentDueDate) {
this.paymentDueDate = paymentDueDate;
}
public Customer getCustomer() {
return this.customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<Product> getProducts() {
return this.products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
OrderOperation.java
package com.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.model.Order;
public interface OrderOperation extends JpaRepository<Order, Long> {
#Query("SELECT c.orders FROM Customer c where c.custIDPK = :id")
public List<Order> findOrderbyID(#Param("id") int id);
}
CustomerController.java
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
ICutomerService customerDAO;
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = { "/", "" }, method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllCustomer() {
return new ResponseEntity(customerDAO.getAllCustomer(), HttpStatus.ACCEPTED);
}
#RequestMapping(value = "/{CustomerById}", method = RequestMethod.GET, produces = { "application/json" })
public Customer getCustomerbyId(#PathVariable("CustomerById") String cid) {
return customerDAO.findCustomerById(Integer.parseInt(cid));
}
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = "{CustomerById}/order", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<?> getAllOrder(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getOrdersbyId(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#RequestMapping(value = "order/{CustomerById}/product", method = RequestMethod.GET, produces = {
"application/json" })
public ResponseEntity<?> getAllProduct(#PathVariable("CustomerById") String cid) {
return new ResponseEntity(customerDAO.getProductsById(Integer.parseInt(cid)), HttpStatus.ACCEPTED);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ResponseEntity<?> addCustomer(#RequestBody Customer c) {
boolean flag = customerDAO.addCustomer(c);
if (flag)
return new ResponseEntity(HttpStatus.CREATED);
else
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
#SuppressWarnings("rawtypes")
#RequestMapping(value = "/{CustomerById}/orders", method = RequestMethod.POST)
public ResponseEntity<?> addOrders(#PathVariable("CustomerById") String cid, #RequestBody Order c) {
// c.getCustomer().setCustIDPK(Integer.parseInt(cid));
boolean flag = customerDAO.addOrder(c);
if (flag) {
return new ResponseEntity(HttpStatus.CREATED);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
How should I design this addOrders method?
If you are using Spring Data then you will need to create a CrudRepository for each table you which to access. The CrudRepository allows you to easily manipulate data in your table using standard ORM practices. Here is a link with more details.
For more detailed info on how to use Spring Data check out this wonderful guide. This guide has become indispensable when working with Spring Data.
There are many options to this but i have used below approach so hope it helps you. The #Query annotation allows to execute native queries by setting the nativeQuery flag to true.
#Query(value = "select o.* from customer c inner join order o on c.customer_id = o.customer_id where o. = ?1", nativeQuery = true)
Please write sql according to your requirement.
Related
I'm using spring boot to construct a database using AWS RDS as well. I want to track down how many stars a user gives to different products. I learnt to go around the many-to-many relationship by creating a table connecting two one-to-many other tables. For this reason, I have created the following tables:
When a user rates a product, an api is called through the put command in order to track down which user(uid) rates which product(pid). When the product(pid) is not rated by anyone, a rate_item is created that contains the pid and also the uid. However, when another user (with a different uid) rates the same product (same pid), the rate_item is updated, which is a problem becausse supposedly, a new row containing the same pid and a different uid should be created, as seen in the following (user with "uid 1" has already rated the same product and when user with "uid 2" rates the same product, the entity gets updated, but not like a new entity is created):
ProductEntity:
#Entity
#Table(name = "product")
public class ProductEntity {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "pid",nullable = false)
private Integer pid;
#Column(name = "name", nullable = false)
private String name;
#Column(name="theme", nullable = false)
private String theme;
#Column(name="color", nullable = false)
private String color;
#Column(name="sizeZero", nullable = true)
private String sizeZero;
#Column(name="sizeOne", nullable = true)
private String sizeOne;
#Column(name="sizeTwo", nullable = true)
private String sizeTwo;
#Column(name="sizeThree", nullable = true)
private String sizeThree;
#Column(name="description",nullable = false)
private String description;
#Column(name = "image_url", nullable = false)
private String imageUrl;
#Column(name = "price",nullable = false)
private BigDecimal price;
#Column(name = "stock",nullable = false)
private Integer stock;
public ProductEntity(CreateProductData createProductData) {
this.pid = createProductData.getPid();
this.name = createProductData.getName();
this.theme =createProductData.getTheme();
this.color=createProductData.getColor();
this.sizeZero=createProductData.getSizeZero();
this.sizeOne =createProductData.getSizeOne();
this.sizeTwo =createProductData.getSizeTwo();
this.sizeThree =createProductData.getSizeThree();
this.description =createProductData.getDescription();
this.imageUrl = createProductData.getImageUrl();
this.price = createProductData.getPrice();
this.stock = createProductData.getStock();
}
public ProductEntity(){
}
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTheme() {
return theme;
}
public void setTheme(String productType) {
this.theme = productType;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSizeZero() {
return sizeZero;
}
public void setSizeZero(String sizeZero) {
this.sizeZero = sizeZero;
}
public String getSizeOne() {
return sizeOne;
}
public void setSizeOne(String smallSize) {
this.sizeOne = smallSize;
}
public String getSizeTwo() {
return sizeTwo;
}
public void setSizeTwo(String mediumSize) {
this.sizeTwo = mediumSize;
}
public String getSizeThree() {
return sizeThree;
}
public void setSizeThree(String largeSize) {
this.sizeThree = largeSize;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
}
UserEntity:
#Entity
#Table(name="User")
public class UserEntity {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="uid",nullable = false)
private Integer uid;
#Column(name="username", nullable = false)
private String username;
#Column(name="email", nullable = false, unique = true)
private String email;
#Column(name="password", nullable = false)
private String password;
#Column(name = "firebase_uid", nullable = false)
private String firebaseUid;
#Column(name= "emailVerified", nullable = false,columnDefinition = "boolean default false")
private Boolean emailVerified=false;
#Column(name="subscribed", nullable = false)
private Boolean subscribed;
public UserEntity(UserEntity tempUserEntity){
this.uid=tempUserEntity.getUid();
this.firebaseUid=tempUserEntity.getFirebaseUid();
this.email=tempUserEntity.getEmail();
}
public UserEntity(CreateFirebaseUserData createFirebaseUserData){
this.username=createFirebaseUserData.getUsername();
this.email=createFirebaseUserData.getEmail();
this.password=createFirebaseUserData.getPassword();
this.firebaseUid= createFirebaseUserData.getFirebaseUid();
this.subscribed=createFirebaseUserData.getSubscribed();
}
public UserEntity(){
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirebaseUid() {
return firebaseUid;
}
public void setFirebaseUid(String firebaseUid) {
this.firebaseUid = firebaseUid;
}
public Boolean getEmailVerified() {
return emailVerified;
}
public void setEmailVerified(Boolean emailVerified) {
this.emailVerified = emailVerified;
}
public Boolean getSubscribed() {
return subscribed;
}
public void setSubscribed(Boolean subscribed) {
this.subscribed = subscribed;
}
}
RatingEntity:
#Entity
#Table(name="Rating")
public class ProductsRatedByUserEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="pruid")
private Integer pruid;
#OneToOne
#JoinColumn(name="pid",nullable = false)
private ProductEntity product;
#ManyToOne
#JoinColumn(name="uid",nullable = false)
private UserEntity user;
#Column
private Integer starsGiven;
#Column(name="total_stars", nullable = false)
private Integer totalStars;
#Column(name="total_num_of_users_who_rated", nullable = false)
private Integer totalNumOfUsersWhoRated;
#Column(name="average_stars")
private BigDecimal averageStars;
public ProductsRatedByUserEntity(UserEntity userEntity, ProductEntity productEntity, Integer numOfStars){
this.product=productEntity;
this.user=userEntity;
this.starsGiven=numOfStars;
this.totalStars=numOfStars;
this.totalNumOfUsersWhoRated=1;
this.averageStars=BigDecimal.valueOf(this.getTotalStars()).divide(BigDecimal.valueOf(this.getTotalNumOfUsersWhoRated()));
}
public ProductsRatedByUserEntity(ProductEntity product,UserEntity user,Integer numOfStars,Integer newTotalNumOfStars, Integer newTotalNumberOfUsers, BigDecimal averageStars){
this.product=product;
this.user=user;
this.starsGiven=numOfStars;
this.totalStars=newTotalNumOfStars;
this.totalNumOfUsersWhoRated=newTotalNumberOfUsers;
this.averageStars=averageStars;
}
public ProductsRatedByUserEntity(){
}
public Integer getPruid() {
return pruid;
}
public void setPruid(Integer plbuid) {
this.pruid = plbuid;
}
public ProductEntity getProduct() {
return product;
}
public void setProduct(ProductEntity product) {
this.product = product;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public Integer getStarsGiven() {
return starsGiven;
}
public void setStarsGiven(Integer starsGiven) {
this.starsGiven = starsGiven;
}
public Integer getTotalStars() {
return totalStars;
}
public void setTotalStars(Integer totalStars) {
this.totalStars = totalStars;
}
public Integer getTotalNumOfUsersWhoRated() {
return totalNumOfUsersWhoRated;
}
public void setTotalNumOfUsersWhoRated(Integer totalNumOfUsersWhoLiked) {
this.totalNumOfUsersWhoRated = totalNumOfUsersWhoLiked;
}
public BigDecimal getAverageStars() {
return averageStars;
}
public void setAverageStars(BigDecimal averageStars) {
this.averageStars = averageStars;
}
}
Api:
#CrossOrigin
#RestController
public class ProductApi {
private ProductService productService;
private ProductsRatedByUserService productsRatedByUserService;
#Autowired
public ProductApi(ProductService productService,ProductsRatedByUserService productsRatedByUserService){
this.productService=productService;
this.productsRatedByUserService=productsRatedByUserService;
}
#PutMapping("/product/rating/{pid}/{numOfStars}")
public ProductsRatedByUserResponseDto updateRating(#PathVariable Integer pid, #PathVariable Integer numOfStars, JwtAuthenticationToken jwtAuthenticationToken) throws ProductFoundByIdException {
FirebaseUserData firebaseUserData=new FirebaseUserData(jwtAuthenticationToken);
ProductsRatedByUserDetail productsRatedByUserDetail=productsRatedByUserService.updateProductRating(pid,numOfStars,firebaseUserData);
return new ProductsRatedByUserResponseDto(productsRatedByUserDetail);
}
}
RatingServiceImpl:
#Service
#Component
public class ProductsRatedByUserServiceImpl implements ProductsRatedByUserService {
public ProductsRatedByUserRepository productsRatedByUserRepository;
public ProductRepository productRepository;
public UserRepository userRepository;
#Autowired
public ProductsRatedByUserServiceImpl(ProductsRatedByUserRepository productsRatedByUserRepository,ProductRepository productRepository,UserRepository userRepository){
this.productsRatedByUserRepository=productsRatedByUserRepository;
this.productRepository=productRepository;
this.userRepository=userRepository;
}
#Override
public ProductsRatedByUserDetail updateProductRating(Integer pid, Integer numOfStars, FirebaseUserData firebaseUserData) throws ProductFoundByIdException {
if(!productRepository.existsById(pid)){
throw new ProductFoundByIdException();
}
UserEntity userEntity=userRepository.findUserEntityByEmail(firebaseUserData.getEmail());
ProductEntity productEntity =productRepository.findById(pid).orElse(null);
//check if the product has been rated by *any user*
//If no, we need to create an entity
if(!productsRatedByUserRepository.existsByProduct(productEntity)){
ProductsRatedByUserEntity productsRatedByUserEntity=new ProductsRatedByUserEntity(userEntity, productEntity, numOfStars);
ProductsRatedByUserEntity productsRatedByUserEntityReturned=productsRatedByUserRepository.save(productsRatedByUserEntity);
System.out.println("the product has been rated by *any user*");
return new ProductsRatedByUserDetail(productsRatedByUserEntityReturned);
}
//If yes, we update the entity from there
else {
//if the product has been rated by this very user
if (productsRatedByUserRepository.existsByUserAndProduct(userEntity, productEntity)) {
ProductsRatedByUserEntity productsRatedByUserEntity = productsRatedByUserRepository.findTopByUserAndProduct(userEntity, productEntity);
productsRatedByUserEntity.setTotalStars(productsRatedByUserEntity.getTotalStars() - productsRatedByUserEntity.getStarsGiven() + numOfStars);
productsRatedByUserEntity.setStarsGiven(numOfStars);
productsRatedByUserEntity.setAverageStars(BigDecimal.valueOf(productsRatedByUserEntity.getTotalStars()).divide(BigDecimal.valueOf(productsRatedByUserEntity.getTotalNumOfUsersWhoRated())));
ProductsRatedByUserEntity productsRatedByUserEntityReturned = productsRatedByUserRepository.save(productsRatedByUserEntity);
System.out.println("the product has been rated by this very user");
return new ProductsRatedByUserDetail(productsRatedByUserEntityReturned);
} else {
//The product has not been rated by this very user
ProductsRatedByUserEntity productsRatedByUserEntity = productsRatedByUserRepository.findTopByProduct(productEntity);
int newTotalNumOfStars = (productsRatedByUserEntity.getTotalStars() + numOfStars);
int newTotalNumberOfUsers = productsRatedByUserEntity.getTotalNumOfUsersWhoRated() + 1;
productsRatedByUserEntity.setUser(userEntity);
System.out.println("The product has not been rated by this very user");
return new ProductsRatedByUserDetail(productsRatedByUserRepository.save(new ProductsRatedByUserEntity(productEntity, userEntity, numOfStars, newTotalNumOfStars, newTotalNumberOfUsers, BigDecimal.valueOf(newTotalNumOfStars).divide(BigDecimal.valueOf(newTotalNumberOfUsers)))));
}
}
}
}
RatingServiceInterface:
public interface ProductsRatedByUserService {
ProductsRatedByUserDetail updateProductRating(Integer pid, Integer numOfStars, FirebaseUserData firebaseUserData) throws ProductFoundByIdException;
}
Repository:
public interface ProductsRatedByUserRepository extends CrudRepository<ProductsRatedByUserEntity,Integer> {
boolean existsByProduct(ProductEntity product);
ProductsRatedByUserEntity findTopByProduct(ProductEntity product);
boolean existsByUserAndProduct(UserEntity userEntity, ProductEntity product);
ProductsRatedByUserEntity findTopByUserAndProduct(UserEntity userEntity, ProductEntity product);
}
I will really appreciate anyone who can help me with this! I've been stuck for a whole day! I don't want to use the many-to-many annotation because it seems a bit messy. Thanks!
I have found the mistake. In my RatingEntity code, the getter and setter are erroneous. There's some typos there. It should be
public Integer getPruid() {
return pruid;
}
public void setPruid(Integer pruid) {
this.pruid = pruid;
}
I'm having some trouble to find out how to use an specific query on Springboot
SELECT tb_excursao.fk_cliente, tb_cliente.nome, tb_cliente.documento, tb_cliente.org_emissor, tb_cliente.data_nascimento, tb_excursao.fk_viagem, tb_viagens.destino, tb_viagens.data_viagem
FROM ((tb_excursao
INNER JOIN tb_cliente ON fk_cliente = tb_cliente.id_cliente)
INNER JOIN tb_viagens ON fk_viagem = tb_viagens.id_viagem))
This works fine on MySQL, but the examples that I saw it's always something like "SELECT u FROM User u", and as a beginner I can't relate using columns from different tables using #Query.
The models are below:
Cliente.java
#Entity
#Table(name = "tb_cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idCliente;
#NotBlank
#Size(min = 3)
private String nome;
#NotNull
private String documento;
#NotNull
private String orgEmissor;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataNascimento;
#Temporal(TemporalType.TIMESTAMP)
private Date dataCadastro = new java.sql.Date(System.currentTimeMillis());
#OneToMany(mappedBy = "fkCliente")
Set<Excursao> excursao;
public long getIdCliente() {
return idCliente;
}
public void setIdCliente(long idCliente) {
this.idCliente = idCliente;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDocumento() {
return documento;
}
public void setDocumento(String documento) {
this.documento = documento;
}
public String getOrgEmissor() {
return orgEmissor;
}
public void setOrgEmissor(String orgEmissor) {
this.orgEmissor = orgEmissor;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
}
Viagem.java
#Entity
#Table(name = "tb_viagens")
public class Viagem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idViagem;
#NotBlank
private String destino;
#NotBlank
#JsonFormat(pattern = "dd/MM/yyyy")
private Date dataViagem;
#NotBlank
private int quantidadeMaxPessoas;
#OneToMany(mappedBy = "fkViagem")
private Set<Excursao> excursao;
public long getIdViagem() {
return idViagem;
}
public void setIdViagem(long idViagem) {
this.idViagem = idViagem;
}
public String getDestino() {
return destino;
}
public void setDestino(String destino) {
this.destino = destino;
}
public Date getDataViagem() {
return dataViagem;
}
public void setDataViagem(Date dataViagem) {
this.dataViagem = dataViagem;
}
public int getQuantidadeMaxPessoas() {
return quantidadeMaxPessoas;
}
public void setQuantidadeMaxPessoas(int quantidadeMaxPessoas) {
this.quantidadeMaxPessoas = quantidadeMaxPessoas;
}
}
ExcursaoEmbeddable.java
#Embeddable
public class ExcursaoEmb implements Serializable {
#Column(name = "fkCliente")
private Long fkCliente;
#Column(name = "fkViagem")
private Long fkViagem;
public Long getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Long fkCliente) {
this.fkCliente = fkCliente;
}
public Long getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Long fkViagem) {
this.fkViagem = fkViagem;
}
}
Excursao.java This is the table that the query in the beginning of the post goes
#Entity
#Table(name = "tb_excursao")
public class Excursao {
#EmbeddedId
ExcursaoEmb idExcursao;
#ManyToOne
#JoinColumn(name = "id_cliente")
private Cliente fkCliente;
#ManyToOne
#JoinColumn(name = "id_viagem")
private Viagem fkViagem;
#NotNull
private boolean primeiraParcela;
#NotNull
private boolean segundaParcela;
private boolean terceiraParcela;
public ExcursaoEmb getIdExcursao() {
return this.idExcursao;
}
public void setIdExcursao(ExcursaoEmb idExcursao) {
this.idExcursao = idExcursao;
}
public Cliente getFkCliente() {
return this.fkCliente;
}
public void setFkCliente(Cliente fkCliente) {
this.fkCliente = fkCliente;
}
public Viagem getFkViagem() {
return this.fkViagem;
}
public void setFkViagem(Viagem fkViagem) {
this.fkViagem = fkViagem;
}
public boolean isPrimeiraParcela() {
return this.primeiraParcela;
}
public boolean getPrimeiraParcela() {
return this.primeiraParcela;
}
public void setPrimeiraParcela(boolean primeiraParcela) {
this.primeiraParcela = primeiraParcela;
}
public boolean isSegundaParcela() {
return this.segundaParcela;
}
public boolean getSegundaParcela() {
return this.segundaParcela;
}
public void setSegundaParcela(boolean segundaParcela) {
this.segundaParcela = segundaParcela;
}
public boolean isTerceiraParcela() {
return this.terceiraParcela;
}
public boolean getTerceiraParcela() {
return this.terceiraParcela;
}
public void setTerceiraParcela(boolean terceiraParcela) {
this.terceiraParcela = terceiraParcela;
}
}
I am trying to test my code in spring boot but I catch
java.lang.NullPointerException
exception when I run my code.
here are my Models:
package com.Loyalty.OpenLoyalty.Models.User;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.swing.text.StyledEditorKit;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
#Entity
#Table(name = "ol__user")
#DynamicUpdate
#EntityListeners(AuditingEntityListener.class)
public class ol__user {
public ol__user() {
}
public ol__user(String first_name, String last_name, String Email, String username, String password, String dtype, Boolean is_active,ol__roles role,String salt,Timestamp create_at){
super();
this.first_name=first_name;
this.last_name=last_name;
this.password=password;
this.email=Email;
this.is_active=is_active;
this.username=username;
this.dtype=dtype;
this.role=role;
this.salt=salt;
this.create_at=create_at;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid")
#Column(name = "id", unique = true, nullable = false)
private String id;
#Column(name = "username", nullable = true)
private String username;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "salt", nullable = true)
private String salt;
#Column(name = "is_active", nullable = false)
private Boolean is_active;
#Column(name = "create_at", nullable = true)
private Timestamp create_at;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "password_requested_at", nullable = true)
private Timestamp password_requested_at;
#Column(name = "confirmation_token", nullable = true)
private String confirmation_token;
#Column(name = "deleted_at", nullable = true)
private Timestamp deleted_at;
#Column(name = "last_login_at", nullable = true)
private Timestamp last_login_at;
#Column(name = "dtype", nullable = false)
private String dtype;
#Column(name = "temporary_password_set_at", nullable = true)
private Timestamp temporary_password_set_at;
#Column(name = "action_token", nullable = true)
private String action_token;
#Column(name = "referral_customer_email", nullable = true)
private String referral_customer_email;
#Column(name = "newsletter_used_flag", nullable = true)
private Boolean newsletter_used_flag;
#Column(name = "phone", nullable = true)
private String phone;
#Column(name = "status_type", nullable = true)
private String status_type;
#Column(name = "status_state", nullable = true)
private String status_state;
#Column(name = "first_name", nullable = true)
private String first_name;
#Column(name = "last_name", nullable = true)
private String last_name;
#Column(name = "external", nullable = true)
private Boolean external;
#Column(name = "api_key", nullable = true)
private String api_key;
#Column(name = "allow_point_transfer", nullable = true)
private Boolean allow_point_transfer;
#ManyToOne(cascade = {CascadeType.ALL})
#JoinTable(name="ol__users_roles",
joinColumns={#JoinColumn(name="user_id")},
inverseJoinColumns={#JoinColumn(name="role_id")})
private ol__roles role;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Boolean getIs_active() {
return is_active;
}
public void setIs_active(Boolean is_active) {
this.is_active = is_active;
}
public Timestamp getCreate_at() {
return create_at;
}
public void setCreate_at(Timestamp create_at) {
this.create_at = create_at;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Timestamp getPassword_requested_at() {
return password_requested_at;
}
public void setPassword_requested_at(Timestamp password_requested_at) {
this.password_requested_at = password_requested_at;
}
public String getConfirmation_token() {
return confirmation_token;
}
public void setConfirmation_token(String confirmation_token) {
this.confirmation_token = confirmation_token;
}
public Timestamp getDeleted_at() {
return deleted_at;
}
public void setDeleted_at(Timestamp deleted_at) {
this.deleted_at = deleted_at;
}
public Timestamp getLast_login_at() {
return last_login_at;
}
public void setLast_login_at(Timestamp last_login_at) {
this.last_login_at = last_login_at;
}
public String getDtype() {
return dtype;
}
public void setDtype(String dtype) {
this.dtype = dtype;
}
public Timestamp getTemporary_password_set_at() {
return temporary_password_set_at;
}
public void setTemporary_password_set_at(Timestamp temporary_password_set_at) {
this.temporary_password_set_at = temporary_password_set_at;
}
public String getAction_token() {
return action_token;
}
public void setAction_token(String action_token) {
this.action_token = action_token;
}
public String getReferral_customer_email() {
return referral_customer_email;
}
public void setReferral_customer_email(String referral_customer_email) {
this.referral_customer_email = referral_customer_email;
}
public Boolean getNewsletter_used_flag() {
return newsletter_used_flag;
}
public void setNewsletter_used_flag(Boolean newsletter_used_flag) {
this.newsletter_used_flag = newsletter_used_flag;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStatus_type() {
return status_type;
}
public void setStatus_type(String status_type) {
this.status_type = status_type;
}
public String getStatus_state() {
return status_state;
}
public void setStatus_state(String status_state) {
this.status_state = status_state;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Boolean getExternal() {
return external;
}
public void setExternal(Boolean external) {
this.external = external;
}
public String getApi_key() {
return api_key;
}
public void setApi_key(String api_key) {
this.api_key = api_key;
}
public Boolean getAllow_point_transfer() {
return allow_point_transfer;
}
public void setAllow_point_transfer(Boolean allow_point_transfer) {
this.allow_point_transfer = allow_point_transfer;
}
public ol__roles getRoles() {
return role;
}
public void setRoles(ol__roles role) {
this.role = role;
}
}
and
package com.Loyalty.OpenLoyalty.Models.User.Projections;
import com.Loyalty.OpenLoyalty.Models.User.ol__user;
import java.util.ArrayList;
import java.util.List;
public class ol__users {
private List<ol__user> usersList;
public List<ol__user> getUsersList(){
if (usersList== null){
usersList=new ArrayList<>();
}
return usersList;
}
public void setUsersList(List<ol__user> usersList){
this.usersList= usersList;
}
}
my controller:
#GetMapping("/admin")
public ol__users getAllAdminUsers( ){
return userService.getAllAdminUsers();
}
My Service:
#Service
public class userService {
#Autowired
private userRepository userRepository;
public ol__users getAllAdminUsers( ){
ol__users response = new ol__users();
ArrayList<ol__user> list=new ArrayList<>();
userRepository.find
Bydtype("admin").forEach(e ->list.add(e));
response.setUsersList(list);
return response;
}
}
and my repository:
#Repository
public interface userRepository extends JpaRepository<ol__user, String> {
List<ol__user> findBydtype(String dtype);
Optional<ol__user> findById(String id);
Boolean existsByUsername(String username);
ol__user findByUsername(String username);
ol__user findByEmail(String username);
ol__user findByEmailIgnoreCase(String email);
// #Query(value = "select count(*) as count from ol__user",nativeQuery = true)
}
and finally here is my test code:
ExtendWith(MockitoExtension.class)
#RunWith(MockitoJUnitRunner.class)
public class Ol_userControllerTest {
#InjectMocks
Ol__userController Ol__userController;
#Mock
userRepository userRepository;
#Mock
userService userService;
#Test
#Transactional
public void testFindAll(){
ol__roles role=new ol__roles();
role.setName("tests");
role.setRole("Admin");
role.setIs_master(true);
Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());
ol__user user1=new ol__user("anteaaa","nejatiaan","anteeaaaa#yahoo.com","anteaaaaa","12345","admin",true,role,"123",currentSqlTimestamp);
ol__user user2=new ol__user("Nooria","Rajaee","Nooriaaaa#yahoo.com","Nooriaa","12345","admin",true,role,"123",currentSqlTimestamp);
List<ol__user> list = new ArrayList<ol__user>();
list.addAll(Arrays.asList(user1,user2));
Mockito.when(userRepository.findBydtype(any())).thenReturn(list);
//when
ol__users result = userService.getAllAdminUsers();
//then
assertThat(result.getUsersList().size()).isEqualTo(2);
assertThat(result.getUsersList().get(0).getFirst_name())
.isEqualTo(user1.getFirst_name());
}
}
I have debuted my code and I understood that
Mockito.when(userRepository.findBydtype(any())).thenReturn(list);
stores list in it but then in the next line my result object returns null and then the exception happens.
I wonder where my problem is?
Yes because you are testing the controller and injected mock to the controller, so the service in the controller is mocked and getAllAdminUsers() returns null.
you should write a test for the controller and another for service
ExtendWith(MockitoExtension.class)
#RunWith(MockitoJUnitRunner.class)
public class ControllerTest {
#InjectMocks
private Ol__userController Ol__userController;
#Mock
private userRepository userRepository;
#Mock
private userService userService;
#Test
public void testFindAll(){
// Arrange
ol__roles role=new ol__roles();
role.setName("tests");
role.setRole("Admin");
role.setIs_master(true);
Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());
ol__user user1=new ol__user("anteaaa","nejatiaan","anteeaaaa#yahoo.com","anteaaaaa","12345","admin",true,role,"123",currentSqlTimestamp);
ol__user user2=new ol__user("Nooria","Rajaee","Nooriaaaa#yahoo.com","Nooriaa","12345","admin",true,role,"123",currentSqlTimestamp);
List<ol__user> list = new ArrayList<ol__user>();
list.addAll(Arrays.asList(user1,user2));
Mockito.when(ol__users result = userService.getAllAdminUsers()
).thenReturn(list);
// Act
List<ol__user> actual = Ol__userController.getAllAdminUsers();
// Assert
assertThat(actual.getUsersList().size()).isEqualTo(2);
assertThat(actual.getUsersList().get(0).getFirst_name())
.isEqualTo(user1.getFirst_name());
}
}
, Service test
ExtendWith(MockitoExtension.class)
#RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
#InjectMocks
private userService userService;
#Mock
private userRepository userRepository;
#Test
public void testFindAll(){
// Arrange
ol__roles role=new ol__roles();
role.setName("tests");
role.setRole("Admin");
role.setIs_master(true);
Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());
ol__user user1=new ol__user("anteaaa","nejatiaan","anteeaaaa#yahoo.com","anteaaaaa","12345","admin",true,role,"123",currentSqlTimestamp);
ol__user user2=new ol__user("Nooria","Rajaee","Nooriaaaa#yahoo.com","Nooriaa","12345","admin",true,role,"123",currentSqlTimestamp);
List<ol__user> list = new ArrayList<ol__user>();
list.addAll(Arrays.asList(user1,user2));
when(userRepository.findBydtype(any())).thenReturn(list);
// Act
ol__users result = userService.getAllAdminUsers();
//Assert
assertThat(result.getUsersList().size()).isEqualTo(2);
assertThat(result.getUsersList().get(0).getFirst_name())
.isEqualTo(user1.getFirst_name());
}
}
I have three tables which called SLSNotification,SLSWorkflow and Importer These tables are not any relationships... I want to get three tables for jasper report.. So I create a native query for it.. It works fine on MySQL... But when i add it to the SLSWorkflowRepository retrieve only workflow class only.. I want to get other classes also from this repository... I think it retrieves only because i write this like this
#Query(value = "select * from slsnotification a join sls_wrkflw b on a.snumber = b.snumber join importers c on c.importer_vat_number = a.importervat where a.importervat = :importerVatNumber and a.snumber = :snumber", nativeQuery = true)
Object getForPrint(#Param("snumber") Long snumber,#Param("importerVatNumber") String importerVatNumber);
can i get other classes for SLSIWorkflow getForPrint() methord...
If i wrong please give some onother way...
This is my models
SLSNotification Model
#Entity
#Table(name = "slsnotification")
public class SLSNotification {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(length = 16)
private Long snumber;
#Column(length = 100)
private String serialCord;
private String date;
// #JsonFormat(pattern = "yyyy-MM-dd")
// private Date appPostdate = new Date();
#Column(nullable = false)
private String appPostdate;
#Column(length = 8)
private String cusOffice;
#Column(length = 1)
private String cusSerial;
#Column(length = 50)
private String cusDecNo;
#JsonFormat(pattern = "yyyy-MM-dd")
private Date cusDate;
#Column(length = 300)
private String manufacturer;
#Column(length = 300)
private String exporterAddress;
#Column(length = 20, nullable = false)
private String importerVAT;
#NotEmpty
#Column(length = 20, nullable = false)
private String declarantVAT;
private String declarantDetails;
private String vessel;
private String blNo;
private String loadingPort;
private String tradingCountry;
private String countryOrigin;
private String invoiceNo;
#JsonFormat(pattern = "yyyy-MM-dd")
private Date invoiceDate;
private Double invoiceValue;
public Long getSnumber() {
return snumber;
}
public void setSnumber(Long snumber) {
this.snumber = snumber;
}
public String getSerialCord() {
return serialCord;
}
public void setSerialCord(String serialCord) {
this.serialCord = serialCord;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCusOffice() {
return cusOffice;
}
public void setCusOffice(String cusOffice) {
this.cusOffice = cusOffice;
}
public String getCusSerial() {
return cusSerial;
}
public void setCusSerial(String cusSerial) {
this.cusSerial = cusSerial;
}
public String getCusDecNo() {
return cusDecNo;
}
public void setCusDecNo(String cusDecNo) {
this.cusDecNo = cusDecNo;
}
public Date getCusDate() {
return cusDate;
}
public void setCusDate(Date cusDate) {
this.cusDate = cusDate;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getExporterAddress() {
return exporterAddress;
}
public void setExporterAddress(String exporterAddress) {
this.exporterAddress = exporterAddress;
}
public String getImporterVAT() {
return importerVAT;
}
public void setImporterVAT(String importerVAT) {
this.importerVAT = importerVAT;
}
public String getDeclarantVAT() {
return declarantVAT;
}
public void setDeclarantVAT(String declarantVAT) {
this.declarantVAT = declarantVAT;
}
public String getVessel() {
return vessel;
}
public void setVessel(String vessel) {
this.vessel = vessel;
}
public String getBlNo() {
return blNo;
}
public void setBlNo(String blNo) {
this.blNo = blNo;
}
public String getLoadingPort() {
return loadingPort;
}
public void setLoadingPort(String loadingPort) {
this.loadingPort = loadingPort;
}
public String getTradingCountry() {
return tradingCountry;
}
public void setTradingCountry(String tradingCountry) {
this.tradingCountry = tradingCountry;
}
public String getCountryOrigin() {
return countryOrigin;
}
public void setCountryOrigin(String countryOrigin) {
this.countryOrigin = countryOrigin;
}
public String getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
public Date getInvoiceDate() {
return invoiceDate;
}
public void setInvoiceDate(Date invoiceDate) {
this.invoiceDate = invoiceDate;
}
public Double getInvoiceValue() {
return invoiceValue;
}
public void setInvoiceValue(Double invoiceValue) {
this.invoiceValue = invoiceValue;
}
SLSWorkflow Model
#Entity
#Table(name = "sls_wrkflw")
public class SLSIWorkflow {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long SNumber;
private String qc;
private String inv;
private String manuTr;
private String packList;
private String blAttached;
private String otherDoc;
private String otherDocName;
private String ad;
private String MAUsername;
private String appMan;
private String accptdQc;
private String accptTR;
private String manufacturer;
private String validMark;
private String otherDocBoolean;
private String cnfrmtyTest;
private String dtSampling;
private String otherDocDet;
private String adUsername;
private String recom;
private String reaRec;
private String tests;
private String wfStatus;
public Long getSNumber() {
return SNumber;
}
public void setSNumber(Long SNumber) {
this.SNumber = SNumber;
}
public String getQc() {
return qc;
}
public void setQc(String qc) {
this.qc = qc;
}
public String getInv() {
return inv;
}
public void setInv(String inv) {
this.inv = inv;
}
public String getManuTr() {
return manuTr;
}
public void setManuTr(String manuTr) {
this.manuTr = manuTr;
}
public String getPackList() {
return packList;
}
public void setPackList(String packList) {
this.packList = packList;
}
public String getBlAttached() {
return blAttached;
}
public void setBlAttached(String blAttached) {
this.blAttached = blAttached;
}
public String getMaattachUser() {
return maattachUser;
}
public void setMaattachUser(String maattachUser) {
this.maattachUser = maattachUser;
}
public String getMauser() {
return mauser;
}
public void setMauser(String mauser) {
this.mauser = mauser;
}
public String getMareattachUser() {
return mareattachUser;
}
public void setMareattachUser(String mareattachUser) {
this.mareattachUser = mareattachUser;
}
public String getOtherDoc() {
return otherDoc;
}
public void setOtherDoc(String otherDoc) {
this.otherDoc = otherDoc;
}
public String getOtherDocName() {
return otherDocName;
}
public void setOtherDocName(String otherDocName) {
this.otherDocName = otherDocName;
}
}
Importer Model
#Entity
#Table(name = "importers")
public class Importer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "importer_id")
private long importerId;
private String importerBrc;
#NotEmpty
#Column(unique = true, nullable = false)
private String importerVatNumber;
#Column(nullable = false)
private String category;
private String importerSVatNumber;
#NotEmpty
private String importerName;
private String importerAddress1;
#NotEmpty
private String officePhoneNumber;
#NotEmpty
private String mobilePhoneNumber;
#Email
#NotEmpty
private String email;
#Email
private String optemail1;
#Email
private String optemail2;
#NotEmpty
private String userIDandTime;
#NotEmpty
private String recentUpdateBy;
public String getOptemail1() {
return optemail1;
}
public void setOptemail1(String optemail1) {
this.optemail1 = optemail1;
}
public String getOptemail2() {
return optemail2;
}
public void setOptemail2(String optemail2) {
this.optemail2 = optemail2;
}
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "importer_agents",
joinColumns = {
#JoinColumn(name = "importerId")},
inverseJoinColumns = {
#JoinColumn(name = "agentId")})
private List<Agent> agentList;
public String getImporterBrc() {
return importerBrc;
}
public void setImporterBrc(String importerBrc) {
this.importerBrc = importerBrc;
}
public String getImporterVatNumber() {
return importerVatNumber;
}
public void setImporterVatNumber(String importerVatNumber) {
this.importerVatNumber = importerVatNumber;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getImporterSVatNumber() {
return importerSVatNumber;
}
public void setImporterSVatNumber(String importerSVatNumber) {
this.importerSVatNumber = importerSVatNumber;
}
public String getImporterName() {
return importerName;
}
public void setImporterName(String importerName) {
this.importerName = importerName;
}
public String getImporterAddress1() {
return importerAddress1;
}
public void setImporterAddress1(String importerAddress1) {
this.importerAddress1 = importerAddress1;
}
}
SLSIWorkflowRepository
public interface SLSIWorkflowRepository extends CrudRepository<SLSIWorkflow,Long> {
#Override
SLSIWorkflow save(SLSIWorkflow slsiWorkflow);
#Override
SLSIWorkflow findOne(Long Long);
#Override
boolean exists(Long Long);
#Override
Iterable<SLSIWorkflow> findAll();
#Override
long count();
#Override
void delete(SLSIWorkflow entity);
#Query(value = "select * from slsnotification a join sls_wrkflw b on a.snumber = b.snumber join importers c on c.importer_vat_number = a.importervat where a.importervat = :importerVatNumber and a.snumber = :snumber", nativeQuery = true)
Object getForPrint(#Param("snumber") Long snumber,#Param("importerVatNumber") String importerVatNumber);
WorkflowServices
public class WorkflowServices {
private static final Logger serviceLogger = LogManager.getLogger(WorkflowServices.class);
private static final String INIT_WORKFLOW_STATUS = "INIT";
#Autowired
private SLSIWorkflowRepository workflowRepository;
#Autowired
private FileSystemStorageService storageService;
#Autowired
private SLSNotificationRepository slsNotificationRepository;
public void initWorkflow(Long slsNumber) {
SLSIWorkflow workflow = new SLSIWorkflow();
workflow.setSNumber(slsNumber);
workflow.setWfStatus(INIT_WORKFLOW_STATUS);
workflowRepository.save(workflow);
}
public SLSIWorkflow getApplicationForPrint(Long SNumber, String importerVatNumber) {
return workflowRepository.getForPrint(SNumber, importerVatNumber);
}
}
Workflow Controller //this is large and i gives my cord only
#RequestMapping(path = "/viewTAXInvoice/{snumber}/{importerVatNumber}", method = RequestMethod.POST)
public ModelAndView getPDFReport(#PathVariable("snumber") String snumber, #PathVariable("importerVatNumber") String importerVatNumber) {
File reportsDir = Paths.get(servletContext.getRealPath(reportDataLocation)).toFile();
if (!reportsDir.exists()) {
throw ProductWithSameSerialExistsException.getInstance();
}
JRDataSource dataSource = new JRBeanCollectionDataSource(Arrays.asList(workflowServices.getApplicationForPrint(Long.parseLong(snumber), importerVatNumber)));
Map<String, Object> parameterMap = new HashMap<>();
parameterMap.put("datasource", dataSource);
parameterMap.put("JasperCustomSubReportDatasource", dataSource);
parameterMap.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(reportsDir));
System.out.println("Dt Source1 "+dataSource);
return new ModelAndView("pdfReportforVAT", parameterMap);
}
How to connect three tables... Please help me someone...
You are getting a SLSIWorkflow only because you are returning that Entity only in the following code in WorkflowServices.
public SLSIWorkflow getApplicationForPrint(Long SNumber, String importerVatNumber) {
return workflowRepository.getForPrint(SNumber, importerVatNumber);
}
If you return an Object it will have all the fields from tables slsnotification, sls_wrkflw, importers as a Object[].
Plus using a Plain JOIN it will result in an INNER JOIN by default. This will not return anything if one joined table doesn't satisfy the ON criteria. It is good if you use LEFT JOIN so that the null will be returned.
I have three entity classes, I have written the query which includes join of two tables.
Table: ExpensesCategories
#Entity
#Table(name = "ExpensesCategories")
public class ExpensesCategories {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "category_id", unique = true)
private int categoryId;
#NotNull
private String categoryName;
#NotNull
private String categoryCodeInBankStats;
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryCodeInBankStats() {
return categoryCodeInBankStats;
}
public void setCategoryCodeInBankStats(String categoryCodeInBankStats) {
this.categoryCodeInBankStats = categoryCodeInBankStats;
}
}
Table: Transactions
#Entity
#Table(name = "TransactionHistory")
public class TransactionHistory {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Temporal(TemporalType.DATE)
private Date dateOfTransaction;
private String transactionType;
private String refNo;
private Date valueDate;
private double withdrawalAmount;
private double depositAmount;
private double closingBalance;
#ManyToOne
#JoinColumn(name="userDetailsId", referencedColumnName="user_id")
private UserDetails userDetails;
#ManyToOne
#JoinColumn(name="expenseCategoriesId", referencedColumnName="category_id")
private ExpensesCategories expenseCategories;
public TransactionHistory(int userId, Date dateOfTransaction, String transactionType, String refNo, Date valueDate,
double withdrawalAmount, double depositAmount, double closingBalance) {
this.dateOfTransaction = dateOfTransaction;
this.transactionType = transactionType;
this.refNo = refNo;
this.valueDate = valueDate;
this.withdrawalAmount = withdrawalAmount;
this.depositAmount = depositAmount;
this.closingBalance = closingBalance;
}
public TransactionHistory() {
}
public Date getDateOfTransaction() {
return dateOfTransaction;
}
public void setDateOfTransaction(Date date) {
this.dateOfTransaction = date;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public String getRefNo() {
return refNo;
}
public void setRefNo(String refNo) {
this.refNo = refNo;
}
public Date getValueDate() {
return valueDate;
}
public void setValueDate(Date valueDate) {
this.valueDate = valueDate;
}
public double getWithdrawalAmount() {
return withdrawalAmount;
}
public void setWithdrawalAmount(double withdrawalAmount) {
this.withdrawalAmount = withdrawalAmount;
}
public double getDepositAmount() {
return depositAmount;
}
public void setDepositAmount(double depositAmount) {
this.depositAmount = depositAmount;
}
public double getClosingBalance() {
return closingBalance;
}
public void setClosingBalance(double closingBalance) {
this.closingBalance = closingBalance;
}
public UserDetails getUserDetails() {
return userDetails;
}
public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ExpensesCategories getExpenseCategories() {
return expenseCategories;
}
public void setExpenseCategories(ExpensesCategories expenseCategories) {
this.expenseCategories = expenseCategories;
}
}
Table: User Details
#Entity
#Table(name = "Employee")
public class UserDetails {
#Id
#Column(name = "user_id", unique = true)
private int id;
#NotNull
private String firstname;
#NotNull
private String lastname;
#Column(unique = true)
#NotNull
private String emailaddress;
#NotNull
private String role;
public UserDetails(String firstname, String lastname, String emailaddress, String role) {
this.firstname = firstname;
this.lastname = lastname;
this.emailaddress = emailaddress;
this.role = role;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public UserDetails() {
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#Override
public String toString() {
return "Employee [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", emailaddress="
+ emailaddress + ", role=" + role + "]";
}
I have written query like this in transaction entity.
#Query( nativeQuery=true, value="SELECT a.expense_categories_id, a.Total_withdrawal_Amount, b.category_code_in_bank_stats, b.category_name FROM (SELECT expense_categories_id , SUM(withdrawal_amount) AS Total_withdrawal_Amount FROM transaction_history GROUP BY expense_categories_id) a join expenses_categories b on a.expense_categories_id = b.category_id
")
List<Object[]> getCategorizedExpenses();
My Json Response is like:
[
[
1,
21,
"UPI",
"UPI Payments"
],
[
2,
3733.59,
"POS",
"Shopping"
]
]
But i want json response with column names as well:
[
[
expense_categories_id: 1,
Total_withdrawal_Amount: 21,
category_code_in_bank_stats: "UPI",
category_name: "UPI Payments"
],
[
expense_categories_id: 2,
Total_withdrawal_Amount: 3733.59,
category_code_in_bank_stats: "POS",
category_name: "Shopping"
]
]
Please help me out..
You would need to map the results directly to a POJO class and ad some json config:
1) Define the pojo
public ResultClass implements Serializable{
#JsonProperty("expense_categories_id")
private Integer expenseCategoriesId;
...
public ResultClass(Integer expenseCategoriesId ... // rest params){
this.expenseCategoriesId = expenseCategoriesId;
...
}
}
2) Define the mapping:
#SqlResultSetMapping(
name="myMapping",
classes={
#ConstructorResult(
targetClass=ResultClass.class,
columns={
#ColumnResult(name="expenseCategoriesId"),
#ColumnResult(name="totalWithdrawalAmount")
// further mappings ...
}
)
}
)
3) Define a native query
#NamedNativeQuery(name="TransactionHistory.myQuery"
, query="SELECT new mypackage.ResultClass(a.expense_categories_id as expeneCategoriesId ... ) from ...")
4) Define this method in the CrudRepository without the #Query annotation:
public List<ResultClass> myQuery();
Teh #SqlResultSetMapping and #NamedNativeQuery would need to be defined on one of your mapped entities.
Your native query will give you an object[][] as an result. So, it actually a mxn rows.
So,
I think you should create a class names Response
public class Response{
private Long expense_categories_id;
private Double Total_withdrawal_Amount;
private String category_code_in_bank_stats;
private String category_name;
//getters and setters for all attributes
}
List<Response> fillCategorizedExpenses(){
List<Response> response_List = new ArrayList<>();
Response response = null;
Object[][] // fill each object with by accessing their index from
//this array.
for() //iterate the object array. {
response = new Response();
response.setExpense_categories_id(value); // set all attributes.
....
....
....
response_List.add(response);
}
return response_List; //this will print as you need in your project.
}
Thank You :) Hope this might help you out.