Class sorting JSON by ID instead of highest value - java

I'm doing a vote counting system, the winner is the one who has more than 3 votes, however, I'm facing the following problem. When there is more than one place with 3 votes, instead of my JSON returning the one with the most votes, it always returns the one with more than 3 votes ordered by ID.
That is, if the restaurant with ID 1 has 3 votes, and the restaurant with ID 2 has 10 votes, the restaurant with ID 1 ends up appearing on the route /restaurants/winner despite not being the most voted, is there any way I can make the most voted show up?
e.g: return from /restaurants/winner route
{
"id": 1,
"restaurant": "Burger King",
"address": "Av. Ipiranga, 1600",
"website": "https://www.burgerking.com.br/",
"description": "Rede de fast-food famosa com hambúrgueres grelhados, batata frita e milk-shakes.",
"count": 3
}
While McDonalds has 5 votes
{
"id": 2,
"restaurant": "McDonalds",
"address": "Av. Ipiranga, 5200",
"website": "https://www.mcdonalds.com.br/",
"description": "Rede de fast-food tradicional conhecida por ter ótimos hambúrgueres e batatas fritas.",
"count": 5
}
Here are the classes that I'm using:
Restaurant.java
package com.dbserver.restaurantes.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name = "db_restaurants")
public class Restaurant {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
#JsonIgnore
#OneToMany(mappedBy = "id.restaurant")
private Set<Vote> votes = new HashSet<>();
public Restaurant() {
}
public Restaurant(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Set<Vote> getVotes() {
return votes;
}
}
RestaurantDTO.java
package com.dbserver.restaurantes.dto;
import com.dbserver.restaurantes.entities.Restaurant;
public class RestaurantDTO {
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
public RestaurantDTO() {
}
public RestaurantDTO(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public RestaurantDTO(Restaurant restaurantDTO) {
id = restaurantDTO.getId();
restaurant = restaurantDTO.getRestaurant();
address = restaurantDTO.getAddress();
website = restaurantDTO.getWebsite();
description = restaurantDTO.getDescription();
count = restaurantDTO.getCount();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
RestaurantServices.java
package com.dbserver.restaurantes.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.exceptions.NotFoundException;
import com.dbserver.restaurantes.repositories.RestaurantRepository;
#Service
public class RestaurantServices {
#Autowired
private RestaurantRepository repository;
#Transactional(readOnly = true)
public Page<RestaurantDTO> findAll(Pageable pageable) {
Page<Restaurant> result = repository.findAll(pageable);
Page<RestaurantDTO> page = result.map(x -> new RestaurantDTO(x));
return page;
}
#Transactional(readOnly = true)
public RestaurantDTO findById(Long id) {
Restaurant result = repository.findById(id).get();
RestaurantDTO dto = new RestaurantDTO(result);
return dto;
}
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = repository.findAll();
for (Restaurant restaurant : restaurants) {
// Hibernate.initialize(restaurant.getCount());
if (restaurant.getCount() >= 3) {
return restaurant;
}
}
throw new NotFoundException(
"Nenhum restaurante ganhou a votação, é necessário um total de 3 votos para ter um restaurante vencedor.");
}
#Transactional
public Restaurant addRestaurant(Restaurant newRestaurant) {
return repository.saveAndFlush(newRestaurant);
}
}
RestaurantRepository.java
package com.dbserver.restaurantes.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.dbserver.restaurantes.entities.Restaurant;
public interface RestaurantRepository extends JpaRepository<Restaurant, Long> {
}
RestaurantController.java
package com.dbserver.restaurantes.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.services.RestaurantServices;
#RestController
#RequestMapping(value = "/restaurants")
public class RestaurantController {
#Autowired
private RestaurantServices service;
#GetMapping
public Page<RestaurantDTO> findAll(Pageable pageable) {
return service.findAll(pageable);
}
#GetMapping(value = "/{id}")
public RestaurantDTO findById(#PathVariable Long id) {
return service.findById(id);
}
#GetMapping(value = "/winner")
public Restaurant findWinner(Integer count) {
return service.findWinner(count);
};
#PostMapping
public Restaurant addRestaurant(#RequestBody Restaurant newRestaurant) {
return service.addRestaurant(newRestaurant);
}
}

You have to check the top value as well. So You need to add your own query for that. Here is the code
public interface RestaurantRepository extends JpaRepository<Restaurant, Long>
{
Optional<Restaurant> findFirstByCountGreaterThanEqualOrderByCountDesc (Integer count);
}
and Use that inside your method
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) throws NotFoundException
{
Optional<Restaurant> data = repository.findFirstByCountGreaterThanEqualOrderByCountDesc(3);
if (data.isPresent())
{
return data.get();
}
throw new NotFoundException("Nenhum restaurante ganhou a votação, é necessário um total de 3 votos para ter um restaurante vencedor.");
}
You can use native queries as well.

Related

Filter orders to a one day period - SpringBoot JPA MYSQL

I'm trying to retrieve a list of just the orders created from one day ago till today, and I can't manage to find any help about it, tried everything I found already.
Basically I need a getAllOrders(), but with filtered by that time period, one day....
How do I filter it ? I Found tons of tutorials on how to sort them descending or ascending, nothing else.
My order.java:
package com.proj.my.model;
import java.time.LocalDate;
import java.util.List;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OneToOne;
import jakarta.persistence.Table;
import lombok.ToString;
#ToString
#Entity
#Table(name = "myorder")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt"},
allowGetters = true)
public class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#OneToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "userId")
private User user;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = ShoppingCart.class)
#JoinColumn(name = "order_id")
private List<ShoppingCart> cartItems;
#CreationTimestamp
#Column(updatable = false, name = "createdAt")
private LocalDate createdAt;
public LocalDate getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDate createdAt) {
this.createdAt = createdAt;
}
public Order() {
}
public Order(User user, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.user = user;
this.cartItems = cartItems;
this.createdAt = createdAt;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setCustomer(User user) {
this.user = user;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
}
My orderservice.java
package com.proj.my.service;
import com.proj.my.model.Order;
import com.proj.my.model.CloudProduct;
import com.proj.my.model.ShoppingCart;
import com.proj.my.repository.OrderRepository;
import com.proj.my.repository.CloudProductRepository;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
#Service
public class OrderService {
private OrderRepository orderRepository;
private CloudProductRepository cloudProductRepository;
public OrderService(OrderRepository orderRepository, CloudProductRepository cloudProductRepository) {
this.orderRepository = orderRepository;
this.cloudProductRepository = cloudProductRepository;
}
public Order getOrderDetail(int orderId) {
Optional<Order> order = this.orderRepository.findById(orderId);
return order.isPresent() ? order.get() : null;
}
/* #Query(value = "from order t where Date BETWEEN :yesterday AND :now")
public List<Order> getAllBetweenDates(#Param("yesterday")Date yesterday,#Param("now")Date localdate.now){
private LocalDate yesterday = now.minus(1, ChronoUnit.DAYS);
return orderRepository.findAll();
} */
public List<Order> getAllOrderDetail() {
return orderRepository.findAll();
}
public float getCartAmount(List<ShoppingCart> shoppingCartList) {
float totalCartAmount = 0f;
float singleCartAmount = 0f;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()) {
CloudProduct cloudproduct = product.get();
singleCartAmount = cart.getQuantity() * cloudproduct.getpriceInEuros();
totalCartAmount = totalCartAmount + singleCartAmount;
cart.setProductId(cloudproduct.getProductId());
cart.setAmount(singleCartAmount);
cloudProductRepository.save(cloudproduct);
}
}
return totalCartAmount;
}
public Order saveOrder(Order order) {
return orderRepository.save(order);
}
}
My orderDTO.java
package com.proj.my.dto;
import com.proj.my.model.ShoppingCart;
import java.util.List;
public class OrderDTO {
private List<ShoppingCart> cartItems;
private String userEmail;
private String userName;
public OrderDTO() {
}
public OrderDTO(List<ShoppingCart> cartItems, String userEmail, String userName) {
this.cartItems = cartItems;
this.userEmail = userEmail;
this.userName = userName;
}
public List<ShoppingCart> getCartItems() {
return cartItems;
}
public void setCartItems(List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
}
public String getuserEmail() {
return userEmail;
}
public void setuserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getuserName() {
return userName;
}
public void setuserName(String userName) {
this.userName = userName;
}
#Override
public String toString() {
return "OrderDTO{" +
", cartItems=" + cartItems +
", userEmail='" + userEmail + '\'' +
", userName='" + userName + '\'' +
'}';
}
}
My shoppingcart.java
package com.proj.my.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
/*#Data
#AllArgsConstructor
#RequiredArgsConstructor
#NoArgsConstructor
*/
#Entity
public class ShoppingCart {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Integer productId;
private String productName;
private int quantity;
private float amount;
public ShoppingCart() {
}
public ShoppingCart(Integer productId, String productName, int quantity, float amount) {
this.productId = productId;
this.productName = productName;
this.quantity = quantity;
this.amount = amount;
}
public ShoppingCart(Integer productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
public ShoppingCart(String productName, int quantity) {
this.productName = productName;
this.quantity = quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
#Override
public String toString() {
return "ShoppingCart{" +
"id=" + id +
", productId=" + productId +
", productName='" + productName + '\'' +
", quantity=" + quantity +
", amount=" + amount +
'}';
}
}
And finally my orderController.java
package com.proj.my.controller;
import java.time.LocalDate;
import java.util.List;
import org.springframework.http.ResponseEntity;
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.proj.my.dto.OrderDTO;
import com.proj.my.dto.ResponseOrderDTO;
import com.proj.my.model.Order;
import com.proj.my.model.User;
import com.proj.my.service.CloudProductService;
import com.proj.my.service.OrderService;
import com.proj.my.service.UserService;
#RestController
#RequestMapping("/api")
public class OrderController {
private OrderService orderService;
private CloudProductService cloudProductService;
private UserService userService;
public OrderController(OrderService orderService, CloudProductService cloudProductService, UserService userService) {
this.orderService = orderService;
this.cloudProductService = cloudProductService;
this.userService = userService;
}
#GetMapping(value = "/getOrder/{orderId}")
public ResponseEntity<Order> getOrderDetails(#PathVariable int orderId) {
Order order = orderService.getOrderDetail(orderId);
return ResponseEntity.ok(order);
}
#GetMapping(value = "/getOrder")
public List<Order> getAllOrderDetails() {
return orderService.getAllOrderDetail();
}
#PostMapping("/placeOrder")
public ResponseEntity<ResponseOrderDTO> placeOrder(#RequestBody OrderDTO orderDTO) {
ResponseOrderDTO responseOrderDTO = new ResponseOrderDTO();
float amount = orderService.getCartAmount(orderDTO.getCartItems());
User user = new User(orderDTO.getuserName(), orderDTO.getuserEmail());
Integer userIdFromDb = userService.isUserPresent(user);
if (userIdFromDb != null) {
user.setUserId(userIdFromDb);
}else{
user = userService.createUser(user);
}
LocalDate createdAt = LocalDate.now();
Order order = new Order(user, createdAt, orderDTO.getCartItems());
order = orderService.saveOrder(order);
responseOrderDTO.setAmount(amount);
responseOrderDTO.setDate(com.proj.my.util.DateUtil.getCurrentDateTime());
responseOrderDTO.setOrderId(order.getId());
return ResponseEntity.ok(responseOrderDTO);
}}
You can add method in OrderRepository interface
public List<Order> findByCreatedAtBetween(LocalDate d1, LocalDate d2)
and call it
orderRepository.findByCreatedAtBetween(today.minusDays(1),today);
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.details

Creating a banking API and have customer have an address. How would I do that?

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String street_number;
private String street_name;
private String city;
private String state;
private String zip;
public Address() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStreet_number() {
return street_number;
}
public void setStreet_number(String street_number) {
this.street_number = street_number;
}
public String getStreet_name() {
return street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
package com.bankingapplicationmain.bankingapplicationmain.models;
import javax.persistence.*;
import java.util.Set;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String first_Name;
private String last_Name;
#OneToMany
private Set<Address> addresses;
public Customer() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
}
So far, I tried to use "many-to-one", "many-to-many", but I guess I am still not sure how these work! My create, delete, methods are working fine, but all customers are missing addresses when I try to fetch them.
What I posted:
{
"id": 1,
"first_name": "Leon",
"last_name": "Hunter",
"address": {
"street_number": "902",
"street_name": "Walker Road",
"city": "Clearfield",
"state": "Pennsylvania",
"zip": "16830"
}
}
VS What I am getting:
{
"id": 1,
"first_name": "Leon",
"last_name": "Hunter"
Any help is really appreciated!
Edit:
import com.bankingapplicationmain.bankingapplicationmain.models.Customer;
import com.bankingapplicationmain.bankingapplicationmain.services.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
CustomerService customerService;
//get all customers
#GetMapping
public ResponseEntity<List<Customer>> getAllCustomers(){
return customerService.getAllCustomers();
}
//get customer by id
#GetMapping("/{id}")
public ResponseEntity<Customer> getCustomerById(#PathVariable Long id){
return customerService.getCustomerById(id);
}
//create customer
#PostMapping
public ResponseEntity<?> createCustomer(#Valid #RequestBody Customer customer) {
return customerService.createCustomer(customer);
}
//edit customer
#PutMapping("/{id}")
public ResponseEntity<?> updateCustomer(#PathVariable Long id, #Valid #RequestBody Customer customer){
return customerService.updateCustomer(customer, id);
}
}
package com.bankingapplicationmain.bankingapplicationmain.services;
import com.bankingapplicationmain.bankingapplicationmain.exceptions.CustomerNotFoundException;
import com.bankingapplicationmain.bankingapplicationmain.models.Customer;
import com.bankingapplicationmain.bankingapplicationmain.repositories.CustomerRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.net.URI;
import java.util.List;
import java.util.Optional;
#Service
public class CustomerService {
private CustomerRepository customerRepository;
private static final Logger logger = LoggerFactory.getLogger(CustomerService.class);
#Autowired
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
protected void verifyCustomer(Long customerId) throws CustomerNotFoundException {
Optional<Customer> customer = customerRepository.findById(customerId);
if(customer.isEmpty()) {
throw new CustomerNotFoundException("Customer with id " + customerId + " not found");
}
}
// Get all customers
public ResponseEntity<List<Customer>> getAllCustomers() {
logger.info("Customer(s) found.");
return new ResponseEntity<>(customerRepository.findAll(), HttpStatus.OK);
}
//get customer by id
public ResponseEntity<Customer> getCustomerById(Long customerId) {
if (customerRepository.findById(customerId).isPresent()) {
logger.info("Customer found.");
customerRepository.findById(customerId);
}
throw new CustomerNotFoundException("Customer with id " + customerId + " not found");
}
public ResponseEntity<?> createCustomer(Customer customer){
logger.info("Customer created.");
customerRepository.save(customer);
HttpHeaders responseHeaders = new HttpHeaders();
URI newCustomerUri = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(customer.getId())
.toUri();
responseHeaders.setLocation(newCustomerUri);
return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
}
public ResponseEntity<?> updateCustomer(Customer customer, Long customerId) {
verifyCustomer(customerId);
logger.info("Customer info updated.");
customerRepository.save(customer);
return new ResponseEntity<>(HttpStatus.OK);
}
}
As requested from others, I have added my service and controller classes as well. Maybe I am doing something wrong in here too.
The example data that you posted would work for a ManyToOne or a OneToOne relationship, but for the code that you posted, you would need something like this:
{
"id": 1,
"first_name": "Leon",
"last_name": "Hunter",
"addresses": [{
"street_number": "902",
"street_name": "Walker Road",
"city": "Clearfield",
"state": "Pennsylvania",
"zip": "16830"
}]
}
I would recommend a one-to-one relationship for the address, this way all data for individual clients will be kept separate.
For example, if you have mum, dad and kid all linked to one address and the kid moves out, you might change their address and change the address for the parents which is unwanted behavior.
As for the Address not showing, what code are you using to retrieve the data?
I suspect because it isn't a primitive value(string) you may need to add a method to combine all the address data into a single string

Find parent element by searching child / Spring boot JPA + PostgresSQL

I am trying to figure out how to find and return all Books that are associated with a specific author name.
{
"bookId": 5,
"bookName": "test2",
"publishYear": 2022,
"publisher": "test2",
"authors": [
{
"id": 5,
"name": "Heny",
"surname": "Blakc"
},
{
"id": 6,
"name": "Garyy",
"surname": "Harrys"
}
]
}
I want to return all books where Garyy is the author.
I am using Spring Boot + Postgres SQL OneToMany annotation.
Would appreciate any suggestions.
AuthorController:
package com.example.demo.controller;
import com.example.demo.entity.AuthorEntity;
import com.example.demo.repository.AuthorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/author")
public class AuthorController {
#Autowired
AuthorRepository authorRepository;
#GetMapping("/all")
public List<AuthorEntity> author(){
return authorRepository.findAll();
}
#PostMapping("/create")
public AuthorEntity createAuthor(#RequestBody AuthorEntity author){
AuthorEntity savedAuthor = authorRepository.save(author);
return savedAuthor;
}
#GetMapping("/find/{author}")
public List<AuthorEntity> findAuthor(#PathVariable(value = "author") String name){
return authorRepository.findByName(name);
}
}
BookController:
package com.example.demo.controller;
import com.example.demo.entity.BookEntity;
import com.example.demo.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/book")
public class BookController {
#Autowired
private BookRepository bookRepository;
#GetMapping("/all")
public List<BookEntity> getAllBooks(){
List<BookEntity> allBookList = bookRepository.findAll();
return allBookList;
}
#GetMapping("/findBook/{name}")
public List<BookEntity> getBookByName(#PathVariable(value = "name")String bookName)
{
return bookRepository.findByBookName(bookName);
}
#GetMapping("/year/{year}")
public List<BookEntity> getBookByYear(#PathVariable(value = "year")Integer year)
{
return bookRepository.findByPublishYear(year);
}
#GetMapping("/publisher/{publisher}")
public List<BookEntity> getBookByPublisher(#PathVariable(value = "publisher")String publisher)
{
return bookRepository.findByPublisher(publisher);
}
#PostMapping("/create-book")
public BookEntity createBook (#RequestBody BookEntity book){
BookEntity savedBook = bookRepository.save(book);
return savedBook;
}
}
AuthorEntity:
package com.example.demo.entity;
import javax.persistence.*;
#Entity
#Table(name = "authors")
public class AuthorEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "surname",nullable = false)
private String surname;
#ManyToOne(fetch =FetchType.LAZY)
private BookEntity books;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
#Override
public String toString() {
return "AuthorEntity{" +
"id=" + id +
", name='" + name + '\'' +
", surname='" + surname + '\'' +
", books=" + books +
'}';
}
}
BookEntity:
package com.example.demo.entity;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(name = "books")
public class BookEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer bookId;
#Column(name = "book_name", nullable = false)
private String bookName;
#Column(name = "publish_year",nullable = false)
private Integer publishYear;
#Column(name = "publisher",nullable = false)
private String publisher;
#OneToMany(targetEntity = AuthorEntity.class, cascade = CascadeType.ALL)
private List<AuthorEntity> authors;
public List<AuthorEntity> getAuthors() {
return authors;
}
public void setAuthors(List<AuthorEntity> authors) {
this.authors = authors;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Integer getPublishYear() {
return publishYear;
}
public void setPublishYear(Integer publishYear) {
this.publishYear = publishYear;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
#Override
public String toString() {
return "BookEntity{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
", publishYear=" + publishYear +
", publisher='" + publisher + '\'' +
", authors=" + authors +
'}';
}
}
AuthorRepository:
package com.example.demo.repository;
import com.example.demo.entity.AuthorEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface AuthorRepository extends JpaRepository<AuthorEntity, Integer> {
List<AuthorEntity> findByName(String name);
}
BookRepository:
package com.example.demo.repository;
import com.example.demo.entity.BookEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookRepository extends JpaRepository<BookEntity, Integer> {
public List<BookEntity> findByBookName(String bookName);
public List<BookEntity> findByPublishYear(Integer year);
public List<BookEntity> findByPublisher(String publisher);
}
There are multiple way to do so , one approach is to use forEach and filter in java itself like
List<BookeEntity> books = getBooks();
books.forEach(e->{
List<AuthorEntity> al= e.getAuthors().stream().filter(ee->ee.getName().equals("Garyy")).collect(Collectors.toList());
e.setAuthors(al);
});
Your database design was wrong. Reality:
1 author wrote one or many books,
1 book wrote by one or many authors.
Therefore, you need an table author-book to convert relationship many-many to 2 relationships: one-many, many-one.
You can see https://www.stat.auckland.ac.nz/~paul/ItDT/HTML/node42.html section 5.6.3.2 Relationships

Not able to set location model to null in contact entity

I am working on a spring mvc app in which I have 2 model classes. Following are my model classes:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
#Entity
#Table(name="Contact")
public class ContactModel {
#Id
#Column(name="contactid")
#GeneratedValue
private int contactId;
#Column(name="contactname")
private String contactName;
#Column(name="contactemail")
private String email;
#Column(name="contactphone")
private String phone;
#ManyToOne
#JoinColumn(name="locationid")
private LocationModel locationModel;
public LocationModel getLocationModel() {
return locationModel;
}
public void setLocationModel(LocationModel locationModel) {
this.locationModel = locationModel;
}
public int getContactId() {
return contactId;
}
public void setContactId(int contactId) {
this.contactId = contactId;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
and LocationModel
import java.util.List;
//import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Cascade;
#Entity
#Table(name="Location")
public class LocationModel {
#Id
#Column(name="locationid")
#GeneratedValue
private int locationId;
#Column(name="locationname")
private String locationName;
#Column(name="locationdesc")
private String locationDescription;
#Column(name="type")
private String locationType;
#Column(name="address")
private String address;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="district")
private String district;
#Column(name="lattitude")
private String lattitude;
#Column(name="longitude")
private String longitude;
#OneToMany(mappedBy = "locationModel")
private List<ContactModel> contactList;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLocationType() {
return locationType;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public void setLocationType(String locationType) {
this.locationType = locationType;
}
public int getLocationId() {
return locationId;
}
public void setLocationId(int locationId) {
this.locationId = locationId;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getLocationDescription() {
return locationDescription;
}
public void setLocationDescription(String locationDescription) {
this.locationDescription = locationDescription;
}
}
On deleting location I want to set location of corresponding contacts to null. I am using following code for this:
public void selLocationToNull(int locationId) throws Exception {
try {
logger.info("deleteContact() begins:");
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("update ContactModel set locationModel=:newLocation where locationModel=:locationId");
query.setParameter("newLocation", null);
query.setParameter("locationId", locationId);
query.executeUpdate();
logger.info("null update query executed...");
} catch (Exception e) {
logger.debug("Error while updating location to null: "
+ e.getMessage());
throw e;
} finally {
}
}
I am getting exception for this:
org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.bizmerlin.scm.model.LocationModel.locationId
Caused by: java.lang.IllegalArgumentException: Can not set int field com.bizmerlin.scm.model.LocationModel.locationId to java.lang.Integer
I have getter method for locationId in my LocationModel class.
How can you set a null to a primitive type? It is generally good practice to use wrapper types for fields in your Entity.
#Id
#Column(name="locationid")
#GeneratedValue
private Integer locationId;
You set in the query's where LocationModel and compare it with int. SHould be
Query query = session.createQuery("update ContactModel set locationModel=:newLocation where locationModel.id=:locationId");
instead. Or pass the LocationModel instance rather than id

Spring MVC Hibernate web application

Spring MVC + Hibernate web application with mysql database.
3 tables (products, members and cart to connect this two). Members table have two different users: admin and customer.
It should be something like Online Store.
To have Administrator and Customer users. Admin entering new, edit and delete products. Customer to list all products and add to cart part.
But before that it should have log in and sign up part. So Admin or Customer can log in or sign up.
So I have welcome page, index.jsp, from which I need links to:
all_products.jsp -> list all products from products table mysql database
signup.jsp -> Add new member form and sending data to members table mysql database.
login.jsp -> Log In form
From login.jsp depending who logged in:
Customer -> index.jsp
Admin -> admin.jsp
admin.jsp -> add.jsp, all_products.jsp with edit and delete option.
add.jsp-> add new product form
I setup up a new project in Netbeans, with Spring mvc and hibernate framework, connect with mysql database, set up server, glassfish... etc...
Then add...
Members.java
package model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity(name="members")
public class Members implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int memberId;
private String userName;
private String password;
private String fullName;
private String email;
private String address;
private String gender;
private String dateOfBirth;
private String memberType;
private Set<Cart> carts = new HashSet<Cart>(0);
public Members() {
}
public Members(int memberId) {
this.memberId = memberId;
}
public Members(int memberId, String userName, String password, String fullName, String email, String address, String gender, String dateOfBirth, String memberType, Set<Cart> carts) {
this.memberId = memberId;
this.userName = userName;
this.password = password;
this.fullName = fullName;
this.email = email;
this.address = address;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
this.memberType = memberType;
this.carts = carts;
}
public int getMemberId() {
return this.memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getMemberType() {
return this.memberType;
}
public void setMemberType(String memberType) {
this.memberType = memberType;
}
public Set<Cart> getCarts() {
return this.carts;
}
public void setCarts(Set<Cart> carts) {
this.carts = carts;
}
}
Products.java
package model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity(name="products")
public class Products implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int productId;
private String productName;
private String productType;
private String description;
private Double price;
private String productColor;
private String productBrand;
private String productSize;
private Integer allProductsQuantity;
private Set<Cart> carts = new HashSet<Cart>(0);
public Products() {
}
public Products(int productId) {
this.productId = productId;
}
public Products(int productId, String productName, String productType, String description, Double price, String productColor, String productBrand, String productSize, Integer allProductsQuantity, Set<Cart> carts) {
this.productId = productId;
this.productName = productName;
this.productType = productType;
this.description = description;
this.price = price;
this.productColor = productColor;
this.productBrand = productBrand;
this.productSize = productSize;
this.allProductsQuantity = allProductsQuantity;
this.carts = carts;
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductType() {
return this.productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return this.price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getProductColor() {
return this.productColor;
}
public void setProductColor(String productColor) {
this.productColor = productColor;
}
public String getProductBrand() {
return this.productBrand;
}
public void setProductBrand(String productBrand) {
this.productBrand = productBrand;
}
public String getProductSize() {
return this.productSize;
}
public void setProductSize(String productSize) {
this.productSize = productSize;
}
public Integer getAllProductsQuantity() {
return this.allProductsQuantity;
}
public void setAllProductsQuantity(Integer allProductsQuantity) {
this.allProductsQuantity = allProductsQuantity;
}
public Set<Cart> getCarts() {
return this.carts;
}
public void setCarts(Set<Cart> carts) {
this.carts = carts;
}
}
Cart.java
package model;
public class Cart implements java.io.Serializable {
private int cartId;
private Members members;
private Products products;
private Integer cartQuantity;
public Cart() {
}
public Cart(int cartId) {
this.cartId = cartId;
}
public Cart(int cartId, Members members, Products products, Integer cartQuantity) {
this.cartId = cartId;
this.members = members;
this.products = products;
this.cartQuantity = cartQuantity;
}
public int getCartId() {
return this.cartId;
}
public void setCartId(int cartId) {
this.cartId = cartId;
}
public Members getMembers() {
return this.members;
}
public void setMembers(Members members) {
this.members = members;
}
public Products getProducts() {
return this.products;
}
public void setProducts(Products products) {
this.products = products;
}
public Integer getCartQuantity() {
return this.cartQuantity;
}
public void setCartQuantity(Integer cartQuantity) {
this.cartQuantity = cartQuantity;
}
}
I add service also for this classes.
MemberService
package service;
import java.util.List;
import model.Members;
public interface MembersService {
public void add(Members members);
public void edit(Members members);
public void delete(int memberId);
public Members getMembers(int memverId);
public List getAllMembers();
}
ProductsService
package service;
import java.util.List;
import model.Products;
public interface ProductsService {
public void add(Products products);
public void edit(Products products);
public void delete(int productId);
public Products getProducts(int productId);
public List getAllProducts();
}
Also add ServiceImpl
MembersServiceImpl
package service;
import DAO.MembersDAO;
import java.util.List;
import javax.jms.Session;
import javax.transaction.Transactional;
import model.Members;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
#Service
public class MembersServiceImpl implements MembersService{
#Autowired
private MembersDAO membersDAO;
#Transactional
public void add(Members members) {
membersDAO.add(members);
}
#Transactional
public void edit(Members members) {
membersDAO.edit(members);
}
#Transactional
public void delete(int productId) {
membersDAO.delete(productId);
}
#Transactional
public Members getMembers(int productId) {
return membersDAO.getMembers(productId);
}
#Transactional
public List getAllMembers() {
return membersDAO.getAllMembers();
}
}
ProductsServiceImpl
package service;
import DAO.ProductsDAO;
import java.util.List;
import javax.jms.Session;
import javax.transaction.Transactional;
import model.Products;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
#Service
public class ProductsServiceImpl implements ProductsService{
#Autowired
private ProductsDAO productsDAO;
#Transactional
public void add(Products products) {
productsDAO.add(products);
}
#Transactional
public void edit(Products products) {
productsDAO.edit(products);
}
#Transactional
public void delete(int productId) {
productsDAO.delete(productId);
}
#Transactional
public Products getProducts(int productId) {
return productsDAO.getProducts(productId);
}
#Transactional
public List getAllProducts() {
return productsDAO.getAllProducts();
}
}
And ProductsContoller
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Products;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import service.ProductsService;
public class ProductsController extends SimpleFormController {
public ProductsController() {
setCommandClass(Products.class);
setCommandName("products");
setSuccessView("products");
setFormView("products");
}
protected ModelAndView products(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
Products products = (Products) command;
ModelAndView mv = new ModelAndView(getSuccessView());
/*ModelAndView addObject = mv.addObject("products", ProductsService.ProductsService(products.getValue()));*/
return mv;
}
#Autowired
private ProductsService productsService;
public void setProductsService(ProductsService productsService) {
this.productsService = productsService;
}
}
Here I am stack.
I also have simple MembersDAO.java, ProductsDAO.java and there implementations.
...and fist question is how to connect two .jsp pages?
How to make simple navigation bar to connect first all my .jsp(view) pages?
To make simple nav bar on header and use on all my pages.
I know i should use spring contorollers...
How to make simple controller that will take me to all_products.jsp from index.jsp and list all products from products table from mysql database???
How to import spring security, log in section in my app?
Also add new product form...
My app is working and deplopying...
I can upload web.xml and servlet.xml but did change things...
Can anyone help me?!
Thank you very much.
in your .jsp. create your navigation. If products on href doesn't work. Then add
${pageContext.request.contextPath}/products
this will be your navigation
<ul>
<li>
Home
</li>
<li>
Products
</li>
<li>
Users
</li>
</ul>
navigation should look like this or depends on what you want
Home
Products
Users
and the simple controller for the views or for your .jsp files.
#RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView home() {
return new ModelAndView("home"); //home.jsp
}
#RequestMapping(value = "/products", method = RequestMethod.GET)
public ModelAndView products() {
return new ModelAndView("products");
}
#RequestMapping(value = "/users", method = RequestMethod.GET)
public ModelAndView users() {
return new ModelAndView("users");
}

Categories