Calculate percent with sum jpql query - postgresql

I have to calculate the percent of (product's quantity/total quantity in database)*100 using jpql query and I didn't have the result that I want.
My query that I used:
#Query(value = "select new com.food.countProduct( product,SUM(p.quantity)/(select SUM(quantity) from Order)*100)from Order p group by p.product")
public class Order
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne (cascade = CascadeType.MERGE)
#OnDelete(action = OnDeleteAction.CASCADE)
#JoinColumn(name="productId")
private Product product;
private int quantity;
#ManyToOne (cascade = CascadeType.MERGE)
#OnDelete(action = OnDeleteAction.CASCADE)
#JoinColumn(name = "reservationId")
private Reservation reservation;
}
public class countProduct
{
private Product product;
private Long quantity;
public countProduct(Product product, Long quantity)
{
this.product = product;
this.quantity = quantity;
}
}

Related

How to use date_format when using JPQL/JPA to do the sum group by month from column date

I have to get the total price in month from a date(LocalDate) yy-mm-dd with jpql query but i can't do it
with jpql with function : function('date_format',p.date,'%Y-%m')
//in the table of entity i have:
public class Reservation {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private double price;
#ManyToOne #JoinColumn(name="userId" )
public User user;
private LocalDate date;
private boolean confirmed;}
the class where i will put the result
public class MonthIncomes {
private LocalDate date ;
private double price;
public MonthIncomes (LocalDate date,double price){
this. date= date;
this.price = price;
}
//what i do in repository
public interface ReservationRepo extends JpaRepository<Reservation, Long> {
#Query(value = "select new com.food.dto.MonthIncomes( function('date_format',date,'%Y-%m'),SUM(p.price)) from Reservation p group by function('date_format',p.date,'%Y-%m')" )
public List<MonthIncomes> getIncomeByMonth();}`

JPA Composite Key: Avoid Unnecessary of Table Creation

I am learning JPA.
I need to create 3 tables, product (pk => id), cart (pk => id), cart_details (pk also fk => product_id, cart_id).
The relation is : One cart can contain multiple cart_details, one cart_details can contain multiple product and one product can be put on multiple cart_details. I need only 3 tables, but JPA creates 4 tables for me: product, cart, cart_details, cart_details_product
#Entity
#Table(name = "product")
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotBlank
#Size(max = 50)
private String name;
#Size(max = 300)
private String description;
#NotNull
private Double price;
private int qty;
#Column(name = "created_date")
private Date createdDate;
#Column(name = "updated_date")
private Date updatedDate;
}
#Entity
#Table(name = "cart")
public class Cart implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "total_price")
private double totalPrice;
#Column(name = "created_date")
private Date createdDate;
#Column(name = "updated_date")
private Date updatedDate;
}
#Entity
#Table(name = "cart_details")
public class CartDetails implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private CartDetailsId id;
#MapsId("cartId")
#ManyToOne
#JoinColumn(name = "cart_id", referencedColumnName = "id", insertable = false, updatable = false)
private Cart cart;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "product_id", referencedColumnName = "id")
private Set<Product> product;
private int quantity;
private double price;
}
#Embeddable
public class CartDetailsId implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "cart_id")
private Long cartId;
#Column(name = "product_id")
private Long productId;
}
How to avoid creation of this table (cart_details_product)? I think i don't need this table.

Why is there a loop in #OneToMany mapping?

I am trying to create a #OneToMany database using JPA. There is a object Flight and a object Passenger.
the code:
#Entity
#Table(name = "passengers")
public class Passenger {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "name")
private String name;
#Column(name = "surname")
private String surname;
private String email;
private String phoneNumber;
private String birthDate;
#ManyToOne(optional = false)
#JoinColumn(name = "flight_id")
private Flight flight;
public Passenger() {
}
public Passenger(String name, String surname, String email, String phoneNumber, String birthDate, Flight flight) {
super();
this.name = name;
this.surname = surname;
this.email = email;
this.phoneNumber = phoneNumber;
this.birthDate = birthDate;
this.flight = flight;
}
#Entity
#Table(name = "flights")
public class Flight {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "flight_id")
private long id;
private String departure;
private String destination;
private String date;
private int capacity;
private float price;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "flight", cascade = CascadeType.ALL)
private Set<Passenger> passengers;
public Flight() {
}
public Flight(String departure, String destination, String date, int capacity, float price) {
super();
this.departure = departure;
this.destination = destination;
this.date = date;
this.capacity = capacity;
this.price = price;
}
this is how I add a new Passenger:
#PostMapping("/flights")
public ResponseEntity<Object> updateFlight(#RequestBody Flight flight) {
long id = flight.getId();
Optional<Flight> flightOptional = flightRepository.findById(id);
if (!flightOptional.isPresent())
return ResponseEntity.notFound().build();
int currentCapacity = flight.getCapacity();
flight.setCapacity(currentCapacity - 1);
for(Passenger passenger : flight.getPassengers()) {
System.out.println(passenger.getName());
}
this.flightRepository.save(flight);
return ResponseEntity.noContent().build();
}
Unfortunately, when I map the flights and passengers, I appear to have a never ending loop. Passengers have the details of the flight and passengers and again flight and then passengers, and so on.
Is there any way I can resolve it? Am I missing anything?
To avoid the cyclic problem Use #JsonManagedReference, #JsonBackReference as below.
Add #JsonManagedReference on Parent class
#JsonManagedReference
#OneToMany(fetch = FetchType.EAGER, mappedBy = "flight", c
ascadee = CascadeType.ALL)
private Set<Passenger> passengers;
Add #JsonBackReference on child class as below
#JsonBackReference
#ManyToOne(optional = false)
#JoinColumn(name = "flight_id")
private Flight flight;

Project data from different tables to a model

I defined my model classes like below.
#Entity
#Table(name = "my_employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name = "emp_address_mapping", joinColumns = #JoinColumn(name = "emp_id"), inverseJoinColumns = #JoinColumn(name = "address_id"))
private List<Address> addresses = new ArrayList<Address>();
.......
.......
}
#Entity
#Table(name = "my_address")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String country;
.....
.....
}
public class EmployeeDetails {
private int empId;
private String name;
private String country;
......
......
}
How can I write a query using #Query annotation to populate all the EmployeeDetails.
public interface EmployeeRepository extends CrudRepository<Employee, Integer> {
#Query("SELECT new com.sample.app.model.EmployeeDetails......")
List<EmployeeDetails> getEmployeeDetails();
}
Create the constructor in EmployeeDetails
public EmployeeDetails(int id,String name,String country){
this.id=id;
this.name=name;
this.country=country;
}
Try this query
To get all employee details:
SELECT new com.sample.app.model.EmployeeDetails(e.id,e.name,a.country) from Employee e,Address a

JPA query with OneToOne lazy

I have this structure of object
#Entity
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long memberId;
private String name;
private boolean man;
private String address;
#OneToOne(fetch = FetchType.LAZY)
private City city;
private String postalCode;
private String phone1;
private String phone2;
private LocalDate birthdate;
private String email;
private String emergencyContactName;
private String emergencyPhone;
private String paymentGatewayKey;
#OneToMany(fetch = FetchType.LAZY)
private List<Contract> contracs;
#OneToOne(fetch = FetchType.LAZY)
private Commerce commerce;
}
#Entity
public class Contract {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long contractId;
private BigDecimal price;
private int frequency;
private int term;
private LocalDate startDate;
private LocalDate endDate;
private int numberOfPayment;
#Enumerated(EnumType.STRING)
private StatusEnum status;
#OneToMany(fetch = FetchType.LAZY,mappedBy = "contract")
private List<Payment> payments;
#ManyToOne
private Member member;
}
#Entity
public class Payment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long paymentId;
private BigDecimal price;
private LocalDate date;
#Enumerated(EnumType.STRING)
private StatusEnum status;
#Enumerated(EnumType.STRING)
private PaymentModeEnum paymentMode;
#ManyToOne
private Contract contract;
#OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private List<Operation> operations;
}
is it possible from a member query to get only the needed contract, payment, city and commerce info?
If member have many contract... i want to get only contract #2...
I started this query but city and commerce are lazy and i don't know what to do with theses fields.
select m from Member m inner join fetch m.contracs c inner join fetch c.payments p where c.contractId = :contractId