Many to Many API Java Spring Boot - java

I'm just learning Spring Boot and doing a small project I got stuck with. I have a many to many relationship between Students and Courses, there is a table in the middle called enrollment for this relationship which takes the student_id and course_id as the primary key. I am creating an API for the above-mentioned. I have next
Class Student
Class Enrollment
Class Course
Class StudentRepository
Class StudentJPAResource
Class Student
package com.myapis.rest.webservices.restfulwebservicesedgar01.student;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment.Enrollment;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STUD_SEQ")
#SequenceGenerator(sequenceName = "student_id_seq", allocationSize = 1, name = "STUD_SEQ")
private Integer studentId;
#Size(min=2, message="Name should have at least two chars")
private String firstName;
private String lastName;
#OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
#JsonIgnore
private List<Enrollment> enrollments = new ArrayList<>();
#Past
private Date birthDate;
public Student() {}
public Student(Integer studentId, String firstName, String lastName, Date birthDate) {
super();
this.studentId = studentId;
this.firstName = firstName;
this.birthDate = birthDate;
}
public Integer getId() {
return studentId;
}
public void setId(Integer id) {
this.studentId = studentId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setfirstName(String firstName) {
this.firstName = firstName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public List<Enrollment> getEnrollments() {
return enrollments;
}
#Override
public String toString() {
return "Student [studentId=" + studentId + ", firstName=" + firstName + ", lastName=" + lastName + ", payments="
+ payments + ", birthDate=" + birthDate + "]";
}
}
Class Enrollment
package com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import com.myapis.rest.webservices.restfulwebservicesedgar01.course.Course;
import com.myapis.rest.webservices.restfulwebservicesedgar01.student.Student;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity(name="Enrollment")
#Table(name="enrollments")
public class Enrollment {
#EmbeddedId
private EnrollmentId id;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("studentId")
#JoinColumn(name="student_id")
#JsonIgnore
private Student student;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("courseId")
#JoinColumn(name="course_id")
#JsonIgnore
private Course course;
#Column(name="enrollment_id")
private Integer enrollmentId;
#Column(name="date_enrollment")
private Date enrollmentDate;
public Enrollment() {}
public Enrollment(Student student, Course course, Integer enrollmentId, Date enrollmentDate) {
super();
this.id = new EnrollmentId(student.getId(), course.getId());
this.student = student;
this.course = course;
this.enrollmentId = enrollmentId;
this.enrollmentDate = enrollmentDate;
}
public EnrollmentId getId() {
return id;
}
public void setId(EnrollmentId id) {
this.id = id;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Integer getEnrollmentId() {
return enrollmentId;
}
public void setEnrollmentId(Integer enrollmentId) {
this.enrollmentId = enrollmentId;
}
public Date getEnrollmentDate() {
return enrollmentDate;
}
public void setEnrollmentDate(Date enrollmentDate) {
this.enrollmentDate = enrollmentDate;
}
#Override
public String toString() {
return "Enrollment [id=" + id + ", student=" + student + ", course=" + course + ", enrollmentId=" + enrollmentId
+ ", enrollmentDate=" + enrollmentDate + "]";
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Enrollment that = (Enrollment) o;
return Objects.equals(student, that.student) &&
Objects.equals(course, that.course);
}
#Override
public int hashCode() {
return Objects.hash(student, course);
}
}
Class Course
package com.myapis.rest.webservices.restfulwebservicesedgar01.course;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment.Enrollment;
import com.myapis.rest.webservices.restfulwebservicesedgar01.student.Student;
#Entity
public class Course {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "COURSE_SEQ")
#SequenceGenerator(sequenceName = "course_id_seq", allocationSize = 1, name = "COURSE_SEQ")
private Integer courseId;
private String courseName;
private String description;
#OneToMany(mappedBy = "course", cascade = CascadeType.ALL)
private List<Enrollment> enrollments = new ArrayList<>();
public Course() {}
public Course(Integer courseId, String courseName, String description) {
super();
this.courseId = courseId;
this.courseName = courseName;
this.description = description;
}
public Integer getId() {
return courseId;
}
public Integer getCourseId() {
return courseId;
}
public void setCourseId(Integer courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Course [courseId=" + courseId + ", courseName=" + courseName + ", description=" + description + "]";
}
}
Class Enrollment
package com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment;
import java.util.Date;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import com.myapis.rest.webservices.restfulwebservicesedgar01.course.Course;
import com.myapis.rest.webservices.restfulwebservicesedgar01.student.Student;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity(name="Enrollment")
#Table(name="enrollments")
public class Enrollment {
#EmbeddedId
private EnrollmentId id;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("studentId")
#JoinColumn(name="student_id")
#JsonIgnore
private Student student;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("courseId")
#JoinColumn(name="course_id")
#JsonIgnore
private Course course;
#Column(name="enrollment_id")
private Integer enrollmentId;
#Column(name="date_enrollment")
private Date enrollmentDate;
public Enrollment() {}
public Enrollment(Student student, Course course, Integer enrollmentId, Date enrollmentDate) {
super();
this.id = new EnrollmentId(student.getId(), course.getId());
this.student = student;
this.course = course;
this.enrollmentId = enrollmentId;
this.enrollmentDate = enrollmentDate;
}
public EnrollmentId getId() {
return id;
}
public void setId(EnrollmentId id) {
this.id = id;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Integer getEnrollmentId() {
return enrollmentId;
}
public void setEnrollmentId(Integer enrollmentId) {
this.enrollmentId = enrollmentId;
}
public Date getEnrollmentDate() {
return enrollmentDate;
}
public void setEnrollmentDate(Date enrollmentDate) {
this.enrollmentDate = enrollmentDate;
}
#Override
public String toString() {
return "Enrollment [id=" + id + ", student=" + student + ", course=" + course + ", enrollmentId=" + enrollmentId
+ ", enrollmentDate=" + enrollmentDate + "]";
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
Enrollment that = (Enrollment) o;
return Objects.equals(student, that.student) &&
Objects.equals(course, that.course);
}
#Override
public int hashCode() {
return Objects.hash(student, course);
}
}
Class StudentRepository
package com.edgarapis.rest.webservices.restfulwebservicesedgar01.student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface StudentRepository extends JpaRepository<Student, Integer>{
}
Class StudentJPAResource
package com.myapis.rest.webservices.restfulwebservicesedgar01.student;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.myapis.rest.webservices.restfulwebservicesedgar01.payment.Payment;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.MapperFeature;
import com.myapis.rest.webservices.restfulwebservicesedgar01.enrollment.Enrollment;
#RestController
public class StudentJPAResource {
#Autowired
private StudentRepository studentRepository;
//retrieve all students
#GetMapping("/jpa/students")
public List<Student> retrieveAllStudents() {
return studentRepository.findAll();
}
//retrieve one user by id from studentRepository
#GetMapping("/jpa/students/{id}")
public EntityModel<Optional<Student>> retriveStudent(#PathVariable int id) {
Optional<Student> student = studentRepository.findById(id);
if(!student.isPresent()) {
throw new StudentNotFoundException("id - " + id);
}
//"all-students", SERVER_PATH + "/students"
//RetrieveAllStudents
EntityModel<Optional<Student>> resource = EntityModel.of(student);
//From the library WebMvcLinkBuilder
WebMvcLinkBuilder linkTo = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).retrieveAllStudents());
resource.add(linkTo.withRel("all-students"));
return resource;
}
//deleting one user by id
#DeleteMapping("/jpa/students/{id}")
public void deleteStudent(#PathVariable int id) {
studentRepository.deleteById(id);
}
//Save one user to the persistence layer
#PostMapping("/jpa/students")
public ResponseEntity<Object> createStudent(#Valid #RequestBody Student student) {
Student savedStudent = studentRepository.save(student);
// /user/{id} -- Response back indicating the user creation was good
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedStudent.getId()).toUri();
return ResponseEntity.created(location).build();
}
//All courses that one specific student is enrolled
#GetMapping("/jpa/students/{id}/enrollments")
public List<Enrollment> retrieveOneStudentCourses(#PathVariable int id) {
Optional<Student> studentOptional = studentRepository.findById(id);
if(!studentOptional.isPresent()) {
throw new StudentNotFoundException("id - " + id);
}
return studentOptional.get().getEnrollments();
}
//All Students with their courses
#GetMapping("/jpa/students/enrollments")
public List<Student> retrieveAllStudentsCourses() {
// How to implement???
}
}
In the class StudentJPAResource, method retrieveOneStudentCourses, I created this method to retrieve the courses of a specific student. I want to create a method to retrieve all the students and the courses that they are enrolled retrieveAllStudentsCourses().
NOTE
Currently, in the class student, I have the notation #JsonIgnore for Enrollment because when I use retrieveAllStudents() the students come up with their enrollments so, this notation prevents this, otherwise, the students will come up with the enrollments (that is actually what I want to do, but using a different method).
Thank you for your help, beforehand.

Related

Unnecessary usage of data on my DB Springboot

So, I'm making an order project, I'm able to create products(id, created_at, deleted, price_in_euros, product_name), and with those products create orders. When I create an order, the products I chose to it become a cartItem(id, amount, productName, product_id, product_name, quantity, order_id). To make this clear, everytime I make an order I create a shoppingCartItem for each product I choose to order. This will saturate my db since if I want to make 2 orders with 30 products each, I'm making 60 different cartItems.
I need to find a way to use a cartItem for different orders if the amount is the same, because 4 cartItems, for example, can be the same product, but with different amounts.
My CloudProduct.java
package com.proj.my.model;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import java.sql.Date;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import jakarta.persistence.Table;
import jakarta.validation.constraints.Pattern;
#Entity
#Table(name="cloud_product_info")
#SQLDelete(sql = "UPDATE cloud_product_info SET deleted = true WHERE product_id=?")
#Where(clause = "deleted=false")
//#FilterDef(name="", parameters = #ParamDef(name="isDeleted", type = "boolean"))
//#Filter(name="deletedBookFilter", condition = "deleted = :isDeleted")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class CloudProduct {
public static Integer id;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer productId;
#Column(unique=true)
private String productName;
private Float priceInEuros;
#CreationTimestamp
#Column(updatable = false, name = "created_at")
private Date createdAt;
private Boolean deleted = Boolean.FALSE;
#JsonIgnore
public Boolean getdeleted() {
return deleted;
}
#JsonIgnore
public void setdeleted(Boolean deleted) {
this.deleted = deleted;
}
public CloudProduct(Integer productId, String productName, Float priceInEuros) {
this.productId = productId;
this.productName = productName;
this.priceInEuros = priceInEuros;
}
public CloudProduct() {
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Float getpriceInEuros() {
return priceInEuros;
}
public void setProductPrice(Float priceInEuros) {
this.priceInEuros = priceInEuros;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Override
public String toString() {
return "Product{" +
"id=" + productId +
", name='" + productName + '\'' +
", price=" + priceInEuros +
'}';
}
}
My 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 Order(int Id, LocalDate createdAt, List<ShoppingCart> cartItems) {
this.cartItems = cartItems;
this.createdAt = createdAt;
this.id = Id;
}
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 shoppingCart.java
package com.proj.my.model;
import org.hibernate.annotations.NotFound;
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 +
'}';
}
}
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.time.LocalDate;
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;
}
public List<Order> getAllOrderDetail(LocalDate dataaa) {
return orderRepository.findAllByCreatedAt(dataaa);
}
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 orderController.java
package com.proj.my.controller;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.CloudProduct;
import com.proj.my.model.Order;
import com.proj.my.model.ShoppingCart;
import com.proj.my.model.User;
import com.proj.my.repository.CloudProductRepository;
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;
#Autowired
private CloudProductRepository cloudProductRepository;
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 = "/getOrders/{dataaa}")
public List<Order> getAllOrderDetails(#PathVariable LocalDate dataaa) {
return orderService.getAllOrderDetail(dataaa);
}
#PostMapping("/placeOrder")
public ResponseEntity<?> placeOrder(#RequestBody OrderDTO orderDTO) {
ResponseOrderDTO responseOrderDTO = new ResponseOrderDTO();
List<ShoppingCart> shoppingCartList = orderDTO.getCartItems();
ShoppingCart shoppingCart;
for (ShoppingCart cart : shoppingCartList) {
String cloudProductName = cart.getProductName();
Optional<CloudProduct> product = cloudProductRepository.findByProductName(cloudProductName);
if (product.isPresent()){
float amount = orderService.getCartAmount(orderDTO.getCartItems());
if(amount > 0){
User user = new User(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);
}
else{
return new ResponseEntity<>("Can't create an order without products.", HttpStatus.OK);
}
}
else{
return new ResponseEntity<>("No Product with such name found.", HttpStatus.OK);
}
}
return null;
}}
Let me know if you need the rest of the services and, or controllers of the other 2 entities.
How can I do this ?

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

Why postman indicated 404 not found

I'm trying to return data from database but this error has occurred I don't know the error is 404 this is my code :
http://localhost:8085/exercices
my Exercice class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "exercice")
public class exercices implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long idExercice;
private String nomExercice;
private String LinkExercice;
#ManyToOne
private patient patient;
public exercices(Long idExercice, String nomExercice, String linkExercice) {
this.idExercice = idExercice;
this.nomExercice = nomExercice;
this.LinkExercice = linkExercice;
this.patient = new patient();
}
public exercices(String nomExercice, String linkExercice) {
this.nomExercice = nomExercice;
LinkExercice = linkExercice;
}
public Long getIdExercice() {
return idExercice;
}
public void setIdExercice(Long idExercice) {
this.idExercice = idExercice;
}
public String getNomExercice() {
return nomExercice;
}
public void setNomExercice(String nomExercice) {
this.nomExercice = nomExercice;
}
public String getLinkExercice() {
return LinkExercice;
}
public void setLinkExercice(String linkExercice) {
LinkExercice = linkExercice;
}
#Override
public String toString() {
return "exercices [LinkExercice=" + LinkExercice + ", idExercice=" + idExercice + ", nomExercice=" + nomExercice
+ "]";
}
}
ExerciceController
import java.util.List;
import org.apache.catalina.connector.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import healthP.Health.Progress.model.exercices;
import healthP.Health.Progress.service.ExerciceService;
#RestController
#RequestMapping()
public class ExerciceController {
#Autowired
private final ExerciceService exserv;
public ExerciceController(ExerciceService exserv) {
this.exserv = exserv;
}
#GetMapping("/exercices")
public ResponseEntity<List<exercices>> getAllExercices() {
List<exercices> ex = this.exserv.findAllExercices();
return new ResponseEntity<>(ex, HttpStatus.OK);
}
}
ExerciceService
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import healthP.Health.Progress.model.exercices;
import healthP.Health.Progress.repo.ExercicesRepo;
#Service
public class ExerciceService {
private final ExercicesRepo ExRepo;
#Autowired
public ExerciceService(ExercicesRepo ExRepo) {
this.ExRepo = ExRepo;
}
public List<exercices> findAllExercices() {
return this.ExRepo.findAll();
}
}
interface
import org.springframework.data.jpa.repository.JpaRepository;
import healthP.Health.Progress.model.exercices;
public interface ExercicesRepo extends JpaRepository<exercices, Long> {
}
and this is patient class because I want also check if the relation between two classes are correcte and spacially in the constructeur of exercice class.
package healthP.Health.Progress.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//import org.hibernate.annotations.Table;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity
#Table(name = "patient")
// #Table(name = patient.TABLE_NAME)
public class patient implements Serializable {
// public static final String TABLE_NAME="PATIENT";
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int score;
#Column(nullable = false, updatable = false)
private Long id;
private String name;
private String email;
private String password;
#Column(nullable = false, updatable = false)
private String codePatient;
public patient() {
}
public patient(String codep, String name, String email, String password) {
this.codePatient = codep;
this.name = name;
this.email = email;
this.password = password;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCodePatient() {
return this.codePatient;
}
public void setCodePatient(String codePatient) {
this.codePatient = codePatient;
}
public void setScore(int score) {
this.score = score;
}
public int getScore() {
return this.score;
}
#Override
public String toString() {
return "{" + " id='" + getId() + "'" + ", name='" + getName() + "'" + ", email='" + getEmail() + "'"
+ ", password='" + getPassword() + "'" + "}";
}
}```
add api-path to requestmapping of ExerciceController , so it becomes
#RequestMapping("/api")
public class ExerciceController {
EDIT:
You need to add default constructor to excercises entity
public exercices(){}
now you can access it as http://localhost:8085/api/exercices
PS: unrelated to question, use singular class name for entity excercise instead of excercises
You can make little changes in your code and follow any of below approach:
1- Remove #RequestMapping()
You can access endpoint : http://localhost:8085/exercices
2- If you want to manage the api versioning then use #RequestMapping("/api/v1")
You can use endpoint: http://localhost:8085/api/v1/exercices

Issues in one-to-many and many-to-one mapping for three entity classes

I have three entity classes Country, State, and City. Now I am trying to display the cities that come under a particular state and states that come under a particular country. but I am facing an error like
org.springframework.dao.DataAccessResourceFailureException:
Could not create JPA EntityManager;
nested exception is org.hibernate.AnnotationException:
#OneToOne or #ManyToOne on com.region.model.State.cities reference
an unknown entity: java.util.List.
Please help me out in one-to-many and many-to-one mapping for the three tables.
package com.region.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "country")
public class Country {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer country_id;
#Column
private String country_name;
// #Column
// private String status="active";
#Transient
private String statusCode;
#Transient
private String statusmessage;
#OneToMany(targetEntity=State.class, mappedBy="country",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
#JsonBackReference
private List<State> states;
public Country() {
}
public Integer getCountry_id() {
return country_id;
}
public void setCountry_id(Integer country_id) {
this.country_id = country_id;
}
public String getCountry_name() {
return country_name;
}
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusmessage() {
return statusmessage;
}
public void setStatusmessage(String statusmessage) {
this.statusmessage = statusmessage;
}
public List<State> getStates() {
return states;
}
public void setStates(List<State> states) {
this.states = states;
}
}
package com.region.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "state")
public class State {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer sk_state_id;
#Column
private String state_name;
#Column
private String country_id;
// #Column
// private String status="active";
#Transient
private String statusCode;
#Transient String statusMessage;
#ManyToOne()
#JoinColumn(name="country_id", referencedColumnName = "country_id", insertable = false, updatable = false)
#JsonManagedReference
#OneToMany(targetEntity=City.class, mappedBy="state",cascade=CascadeType.ALL, fetch = FetchType.LAZY)
private List<City>cities;
private Country country;
public State() {
}
public Integer getSk_state_id() {
return sk_state_id;
}
public void setSk_state_id(Integer sk_state_id) {
this.sk_state_id = sk_state_id;
}
public String getState_name() {
return state_name;
}
public void setState_name(String state_name) {
this.state_name = state_name;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
// public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
// }
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public List<City> getCities() {
return cities;
}
public void setCities(List<City> cities) {
this.cities = cities;
}
}
package com.region.model;
import java.lang.annotation.Repeatable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
#Entity
#Table(name = "city")
public class City {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private Integer sk_city_id;
#Column
private String city_name;
#Column
private String state_id;
#Column
private String country_id;
#Transient
private String statusCode;
#Transient
String statusMessage;
#ManyToOne(targetEntity = State.class)
#JoinColumn(name="state_id", referencedColumnName ="sk_state_id", insertable = false, updatable = false)
private State state;
private Country country;
//private List<State>states;
public City() {
}
public Integer getSk_city_id() {
return sk_city_id;
}
public void setSk_city_id(Integer sk_city_id) {
this.sk_city_id = sk_city_id;
}
public String getCity_name() {
return city_name;
}
public void setCity_name(String city_name) {
this.city_name = city_name;
}
public String getState_id() {
return state_id;
}
public void setState_id(String state_id) {
this.state_id = state_id;
}
public String getCountry_id() {
return country_id;
}
public void setCountry_id(String country_id) {
this.country_id = country_id;
}
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
#Override
public String toString() {
return "City [sk_city_id=" + sk_city_id + ", city_name=" + city_name + ", state_id=" + state_id
+ ", country_id=" + country_id + ", statusCode=" + statusCode + ", statusMessage=" + statusMessage
+ "]";
}
// public List<State> getStates() {
// return states;
// }
// public void setStates(List<State> states) {
// this.states = states;
// }
}
mappedBy is only used once in a relationship between 2 classes, for the class that you want to define the relationship for both. So in the class Countries you probably don't need mappedBy at all, in the class Cities, you should put mappedBy="state", and in the class State it would make sense to put mappedBy="country"

how to fetch all data from database using one to many relation hibernate query

I have two table Parent table is Credit in that table only one row of data is there and another one is child table Debit that contains multiple row of data. how to fetch data from two table which has to match id of parent class and child class and no duplicate is shown from parent class.
I have try with (from Credit,debit) but that can display with duplicate and not properly data is shown based on id.
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}
}
1.CreditDaoImpl.java
package com.rojmat.daoImpl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.rojmat.dao.CreditDao;
import com.rojmat.entity.Credit;
#Repository
public class CreditDaoImpl implements CreditDao{
#Autowired
private SessionFactory sessionFactory;
#Override
public void addCreditDebit(Credit credit) {
try {
sessionFactory.getCurrentSession().saveOrUpdate(credit);
} catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void deleteCreditDebit(int cid) {
/*Credit credit = (Credit)sessionFactory.getCurrentSession().createQuery("from Credit as c LEFT JOIN FETCH c.Debit where c.cid="+cid).uniqueResult();
List<Debit> debits = credit.getDebit();
sessionFactory.getCurrentSession().delete(credit);
debits.forEach((debit) -> {
sessionFactory.getCurrentSession().delete(debit);
});*/
}
#SuppressWarnings("unchecked")
#Override
public List<Credit> getAllCreditDebit() {
List<Credit> credit = sessionFactory.getCurrentSession().createQuery("from Credit,Debit").list();
return credit;
}
}
try this example: you put "distinct" before the property you do not want to be duplicated
//SQL query
select distinct credit.idCredit as idCredit from Credit credit Left Join Debit debit on credit.idCredit= debit.idCredit
//HQL query
#Entity(name = "Credit")
#Table(name = "Credit")
public class Credit{
//if you put #Id --> HQL Query "select credit from Credit credit"
#Column(name = "idCredit")
private Long idCredit;
#Column(name = "label")
private String label;
#OneToMany
#JoinColumns({#JoinColumn(name = "idCredit" ,referencedColumnName = "idCredit")})
List<Debit> debits;
...
}
public class Debit{
....
#Column(name = "idCredit")
private Long idCredit;
...
}
Query query = getSession().createQuery("select distinct credit.idCredit as idCredit, credit.label as label, credit.debits as debits from Credit credit ");
query.setResultTransformer(Transformers.aliasToBean(Credit.class));
return query.list();
package com.rojmat.entity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.core.annotation.Order;
#Entity
#Table(name="credit")
public class Credit extends BaseEntity{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long cid;
#Column #Order
private long openingbalance;
#Column
private Date date;
#Column #Order
private long debittotal;
#Column #Order
private long drawertotal;
#Column #Order
private long debittotalplusdrawertotal;
#Column #Order
private long todaybusiness;
#OneToMany(cascade={CascadeType.ALL})
#JoinTable(name="credit_debit",
joinColumns=#JoinColumn(name="c_id"),
inverseJoinColumns=#JoinColumn(name="d_id"))
/*#JoinColumn(name="cid", referencedColumnName="cid")*/
private List<Debit> debits = new ArrayList<Debit>(Arrays.asList());
public Credit() {
}
public Credit(long cid, long openingbalance, Date date, long debittotal, long drawertotal,
long debittotalplusdrawertotal, long todaybusiness, List<Debit> debits) {
super();
this.cid = cid;
this.openingbalance = openingbalance;
this.date = date;
this.debittotal = debittotal;
this.drawertotal = drawertotal;
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
this.todaybusiness = todaybusiness;
this.debits = debits;
}
public long getCid() {
return cid;
}
public void setCid(long cid) {
this.cid = cid;
}
public long getOpeningbalance() {
return openingbalance;
}
public void setOpeningbalance(long openingbalance) {
this.openingbalance = openingbalance;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public long getDebittotal() {
return debittotal;
}
public void setDebittotal(long debittotal) {
this.debittotal = debittotal;
}
public long getDrawertotal() {
return drawertotal;
}
public void setDrawertotal(long drawertotal) {
this.drawertotal = drawertotal;
}
public long getDebittotalplusdrawertotal() {
return debittotalplusdrawertotal;
}
public void setDebittotalplusdrawertotal(long debittotalplusdrawertotal) {
this.debittotalplusdrawertotal = debittotalplusdrawertotal;
}
public long getTodaybusiness() {
return todaybusiness;
}
public void setTodaybusiness(long todaybusiness) {
this.todaybusiness = todaybusiness;
}
public List<Debit> getDebit() {
return debits;
}
public void setDebit(List<Debit> debit) {
this.debits = debits;
}
/*#Override
public String toString() {
return "Credit [cid=" + cid + ", openingbalance =" + openingbalance + ", date=" + date + ", debittotal= " + debittotal + ", debittotalplusdrawertotal=" + debittotalplusdrawertotal + ", todaybusiness=" + todaybusiness + "]";
}*/
}
package com.rojmat.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="debit")
public class Debit {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column
private long did;
#Column
private String amount;
#Column
private String description;
public Debit() {
}
public Debit(String amount, String description) {
super();
this.amount = amount;
this.description = description;
}
public long getDid() {
return did;
}
public void setDid(long did) {
this.did = did;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/*#Override
public String toString() {
return "Debit [did=" + did + ", amount =" + amount + ", description=" + description + "]";
}*/
}

Categories