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

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();}`

Related

Calculate percent with sum jpql query

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;
}
}

JPA - select where max date

I have the below query which returns a list of bank accounts.
#Query("SELECT bd FROM assign_iban_entity aie INNER JOIN aie.bankData bd WHERE aie.agreementFileId = ?1")
List<BankAccountEntity> findAllBankAccountByAgreementFileId(String agreementFileId);
My entity:
#Entity(name = "bank_data_entity")
public class BankAccountEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String bankDataId;
private Date createdDate;
}
I want to change the query to return only one BankAccountEntity who has the greatest createdDate.

How to query by date using mongo repository in spring boot?

I have developed an application in spring boot with mongo reposotory. I am using spring data jpa. And I declared in many tables createdDate as Date util package in java and date stores in the db as ISO formatted. When I query using mongo repository findByCreatedDate(Date date) which gives no result.
Below is my model class
#Document
public class BarModel extends BaseEntity {
#NotNull
#Size(min = 2, max = 140)
String name;
String address;
String city;
String state;
String zipcode;
String phone;
String description;
String primImage;
#DBRef
Location location;
#DBRef
List<Special> specials;
}
#MappedSuperclass
#EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {
#Id
private String id;
#CreatedBy
private String createdBy = getCurrentAuditor();
#CreatedDate
#DateTimeFormat(iso = ISO.DATE_TIME)
private Date creationTime = new Date();
#CreatedBy
#LastModifiedBy
private String modifiedBy = getCurrentAuditor();
#CreatedDate
#LastModifiedDate
#DateTimeFormat(iso = ISO.DATE_TIME)
private Date modificationTime = new Date();
}
#Transactional
public interface BarModelRepository extends MongoRepository<BarModel, String> {
Page<BarModel> findByCreationTime(Pageable pageable, Date creationtime);
public List<BarModel> findByCreationTime(Date from, Date to);
}

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

JPA JOIN without cross joins

I'm trying to have a relationship between the following tables
COMBINE
#Entity
#NamedQuery(name="Combine.findAll", query="SELECT c FROM Combine c")
#Table(name="COMBINE")
public class Combine implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
private int artistid;
private int automated;
private int eventid;
private int locationid;
#Column(name="main_artist")
private int mainArtist;
public Combine() {
}
Event
#Entity
#NamedQuery(name="Event.findAll", query="SELECT e FROM Event e")
#Table(name="event")
public class Event implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
private boolean active;
private String addbyspider;
private int automated;
#Lob
private String description;
private Timestamp doorsopen;
private Timestamp endtime;
private Timestamp lastfm;
#Column(name="latest_update")
private Timestamp latestUpdate;
private int minimumageid;
private String name;
private Timestamp nolatertime;
private int podiuminfo;
#Column(name="short_description")
private String shortDescription;
#Column(name="sold_out")
private int soldOut;
private Timestamp time;
#Column(name="update_by_bot")
private Timestamp updateByBot;
/* TO DO: LINK NAAR EVENTPRICE */
// public EventPrice getEventPrice() {
// return eventPrice;
// }
//
// public void setEventPrice(EventPrice eventPrice) {
// this.eventPrice = eventPrice;
// }
//
// #OneToOne(mappedBy = "event_price")
// private EventPrice eventPrice;
//bi-directional many-to-many association to Artist
//#ManyToMany(fetch = FetchType.LAZY)
#ManyToMany
#JoinTable(
name="COMBINE"
, joinColumns={
#JoinColumn(name="eventid")
}
, inverseJoinColumns={
#JoinColumn(name="artistid")
}
)
private List<Artist> artists;
#OneToOne
#JoinColumn(name="eventid")
private List<Combine> combine;
//bi-directional many-to-many association to Location
//#ManyToMany(fetch = FetchType.EAGER)
#OneToMany
#JoinTable(
name="COMBINE"
, joinColumns={
#JoinColumn(name="eventid")
}
, inverseJoinColumns={
#JoinColumn(name="locationid")
}
)
private List<Location> locations;
Location
#Entity
#NamedQuery(name="Location.findAll", query="SELECT l FROM Location l")
#Table(name="location")
public class Location implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
private boolean active;
#Column(name="at_owner")
private int atOwner;
#Column(name="bad_ticket_site")
private int badTicketSite;
#Lob
private String description;
private int expectedBotItems;
private int expectedBotRuntime;
#Column(name="last_run")
private Timestamp lastRun;
private String name;
private boolean notPrimaryBot;
private int organisationid;
private short priorityid;
#Column(name="short_description")
private String shortDescription;
#Column(name="spider_by")
private int spiderBy;
What this currently does is generate cross joins with the tables with the following TypedQuery
StringBuffer sb = new StringBuffer();
sb.append("SELECT e FROM Event e, Combine c, Location l ");
sb.append("where e.id = c.eventid and l.id = c.locationid ");
sb.append("and e.time>=NOW() and e.soldOut='0' and e.active>=1");
This generates
select event0_.id as id1_26_,
event0_.active as active2_26_,
event0_.addbyspider as addbyspi3_26_,
event0_.automated as automate4_26_,
event0_.description as descript5_26_,
event0_.doorsopen as doorsope6_26_,
event0_.endtime as endtime7_26_,
event0_.lastfm as lastfm8_26_,
event0_.latest_update as latest_u9_26_,
event0_.minimumageid as minimum10_26_,
event0_.name as name11_26_,
event0_.nolatertime as nolater12_26_,
event0_.podiuminfo as podiumi13_26_,
event0_.short_description as short_d14_26_,
event0_.sold_out as sold_ou15_26_,
event0_.time as time16_26_,
event0_.update_by_bot as update_17_26_
from
event event0_
cross join COMBINE combine1_
cross join location location2_
where event0_.id=combine1_.eventid and location2_.id=combine1_.locationid and event0_.time>=now() and event0_.sold_out='0' and event0_.active>=1 limit ?
I do not want to create CROSS JOINS at all but instead I would like INNER JOIN between the tables. How could I achieve this?
There is something wrong with the OneToOne as it doesn't build to the server. Anyone know why this doesn't work?
#OneToOne
#JoinColumn(name="eventid")
private List<Combine> combine;