I spent many hours to solve my problem but without success. I'd like to achieve something like this (but with ONE row instead of TWO):
My database:
CREATE TABLE odo.d_kryterium_naruszen (
id bigserial primary key,
kryterium text not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
CREATE TABLE odo.d_czynnik_naruszen (
id bigserial primary key,
czynnik text not null,
id_kryterium_naruszen bigint not null references odo.d_kryterium_naruszen(id),
stopien NUMERIC(10,2) not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
CREATE TABLE odo.d_dotkliwosc_naruszenia (
id bigserial primary key,
zakres numrange not null,
ocena text not null,
opis text not null,
wymagane_dzialanie text not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
CREATE TABLE odo.ocena_naruszenia_wynik (
id bigserial primary key,
wartosc_dotkliwosci_naruszenia NUMERIC(10,2) not null,
status_id bigint not null references odo.d_status_oceny_naruszenia(id),
ocena_naruszenia_id bigint not null references odo.ocena_naruszenia(id),
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
create table odo.czynnik_naruszen_wynik(
id bigserial primary key,
ocena_naruszenia_wynik_id bigint not null references odo.ocena_naruszenia_wynik(id),
czynnik_naruszen_id bigint not null references odo.d_czynnik_naruszen(id),
komentarz text,
czynnik_wybrany boolean not null default false
wartosc_wybrana NUMERIC(10,2) not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
And here my entities:
#Data
#Entity
#Table(schema = "odo", name = "d_kryterium_naruszen")
public class ViolationCriterion extends BaseEntity {
#Column(name = "kryterium")
private String criterion;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "id_kryterium_naruszen")
private List<ViolationFactor> violationFactors;
}
#Data
#Entity
#Table(schema = "odo", name = "d_czynnik_naruszen")
public class ViolationFactor extends BaseEntity {
#Column(name = "czynnik")
private String factor;
#Column(name = "stopien")
private float degree;
#OneToMany
#JoinColumn(name = "czynnik_naruszen_id")
private List<IncidentAssessmentFactor> incidentAssessmentFactor;
}
#Data
#Entity
#Table(schema = "odo", name = "czynnik_naruszen_wynik")
public class IncidentAssessmentFactor extends BaseEntity {
#Column(name="komentarz")
private String comment;
#Column(name="czynnik_wybrany")
private Boolean factorIsSelected;
#Column(name = "wartosc_wybrana")
private Float value;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="ocena_naruszenia_wynik_id", updatable=false, insertable=false)
private IncidentAssessment incidentAssessment;
}
#Data
#Entity
#Table(schema = "odo", name = "ocena_naruszenia_wynik")
public class IncidentAssessment extends BaseEntity {
#Column(name="ocena_naruszenia_id")
private Long incidentAssessmentId;
#Column(name = "wartosc_dotkliwosci_naruszenia")
private Float severityDegreeValue;
My repository:
#Repository
public interface ViolationCriterionRepository extends JpaRepository<ViolationCriterion, Long> {
// #Query("select vc from ViolationCriterion vc inner join vc.violationFactors vf inner join vf.incidentAssessmentFactor iaf inner join iaf.incidentAssessment ia where ia.incidentAssessmentId = ?1 group by vc ")
#Query("select vc from ViolationCriterion vc inner join vc.violationFactors vf inner join vf.incidentAssessmentFactor iaf inner join iaf.incidentAssessment ia where ia.incidentAssessmentId = ?1 group by vc ")
// #Query(value = "select kn.kryterium from odo.d_kryterium_naruszen kn join odo.d_czynnik_naruszen cn on kn.id = cn.id_kryterium_naruszen join odo.czynnik_naruszen_wynik cnw on cnw.czynnik_naruszen_id = cn.id join odo.ocena_naruszenia_wynik onw on cnw.ocena_naruszenia_wynik_id = onw.id where onw.ocena_naruszenia_id = ?1 group by kn.id, cn.id, cnw.id, onw.id", nativeQuery = true)
// #Query(value = "select kn.id, kn.kryterium, kn.data_wpr, kn.opr, cn.id, cn.czynnik, cn.stopien, cn.opr, cn.data_wpr, cnw.id, cnw.data_wpr, cnw.opr, cnw.komentarz, cnw.czynnik_wybrany, cnw.wartosc_wybrana, onw.id, onw.data_wpr, onw.opr, onw.ocena_naruszenia_id, onw.wartosc_dotkliwosci_naruszenia from odo.d_kryterium_naruszen kn join odo.d_czynnik_naruszen cn on kn.id = cn.id_kryterium_naruszen join odo.czynnik_naruszen_wynik cnw on cnw.czynnik_naruszen_id = cn.id join odo.ocena_naruszenia_wynik onw on cnw.ocena_naruszenia_wynik_id = onw.id where onw.ocena_naruszenia_id = ?1 group by kn.id, cn.id, cnw.id, onw.id", nativeQuery = true)
List<ViolationCriterion> findIncidentAssessmentByIncidentAssessmentId(Long incidentId);
// List<ViolationCriterion> findByViolationFactorsIncidentAssessmentFactorIncidentAssessmentIncidentAssessmentIdGroupByViolationCriterionCriterion(Long id);
}
And here I call my repository:
List<ViolationCriterion> violationCriteria = violationCriterionRepository.findIncidentAssessmentByIncidentAssessmentId(id);//vi
In a table czynnik_naruszen_wynik I have 2 different rows because I have 2 rows in table ocena_naruszenia_wynik. The problem is that I have multiple values of entity IncidentAssessmentFactor instead of 1
Related
Tree, Treetag and Tag tables with example data
A tree belongs to a given farm and each farm has its own set of tags.
Each tree can have zero or multiple tags attached to it.
Same tag can be attached to multiple trees.
DDL -
DROP TABLE tree_tag;
DROP TABLE tag;
DROP TABLE tree;
DROP TABLE farm;
CREATE TABLE farm (
id VARCHAR2(36 CHAR) NOT NULL,
description VARCHAR2(255 CHAR) NULL,
name VARCHAR2(255 CHAR) NOT NULL,
PRIMARY KEY ( id )
);
CREATE TABLE tree (
id VARCHAR2(36 CHAR) NOT NULL,
name VARCHAR2(255 CHAR) NOT NULL,
description VARCHAR2(255 CHAR) NULL,
farm_id VARCHAR2(36 CHAR) NOT NULL,
PRIMARY KEY ( id )
);
CREATE TABLE tag (
id VARCHAR2(36 CHAR) NOT NULL,
farm_id VARCHAR2(36 CHAR) NOT NULL,
name VARCHAR2(255 CHAR) NOT NULL,
description VARCHAR2(255 CHAR) NULL,
PRIMARY KEY ( id )
);
CREATE TABLE tree_tag (
id VARCHAR2(36 CHAR) NOT NULL,
tag_id VARCHAR2(36 CHAR) NOT NULL,
tree_id VARCHAR2(36 CHAR) NOT NULL,
value VARCHAR2(255 CHAR) NULL,
properties VARCHAR2(1000 CHAR) NULL,
PRIMARY KEY ( id )
);
ALTER TABLE tag ADD CONSTRAINT unq_tag0 UNIQUE ( farm_id,
name );
ALTER TABLE tree_tag ADD CONSTRAINT unq_tree_tag0 UNIQUE ( tag_id,
tree_id );
ALTER TABLE tree ADD CONSTRAINT unq_tree0 UNIQUE ( farm_id,
name );
ALTER TABLE tag
ADD CONSTRAINT fk_tagfarm_id FOREIGN KEY ( farm_id )
REFERENCES farm ( id )
ON DELETE CASCADE;
ALTER TABLE tree_tag
ADD CONSTRAINT fk_tree_tagtree_id FOREIGN KEY ( tree_id )
REFERENCES tree ( id )
ON DELETE CASCADE;
ALTER TABLE tree_tag
ADD CONSTRAINT fk_tree_tagtag_id FOREIGN KEY ( tag_id )
REFERENCES tag ( id )
ON DELETE CASCADE;
INSERT INTO farm (
id,
name
) VALUES (
'farm1',
'farm 1 is big'
);
INSERT INTO farm (
id,
name
) VALUES (
'farm2',
'farm 2 is small'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag11',
'farm1',
'juicy'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag12',
'farm1',
'sour'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag13',
'farm1',
'sweet'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag21',
'farm2',
'sour'
);
INSERT INTO tree (
id,
farm_id,
name,
description
) VALUES (
'tree11',
'farm1',
'apple',
'used for jam'
);
INSERT INTO tree (
id,
farm_id,
name
) VALUES (
'tree12',
'farm1',
'cherry'
);
INSERT INTO tree (
id,
farm_id,
name
) VALUES (
'tree13',
'farm1',
'plum'
);
INSERT INTO tree (
id,
farm_id,
name
) VALUES (
'tree21',
'farm2',
'apple'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'1',
'tree11',
'tag12'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'2',
'tree12',
'tag11'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'3',
'tree12',
'tag13'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'4',
'tree13',
'tag12'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'5',
'tree13',
'tag11'
);
Query:
Want to get a list of trees w/o duplicates where either the name
or the description or the tag name matches the filter in a given
farm
Want to get the count of this unique list of trees in a
given farm
This is a paging request so step 1 query will be called multiple times but step 2 query will be executed only once.
SQL -
This works but when I convert to JPA then subquery is returning all the entries in tree_tag i.e filtering is not happening in JPA subquery
SELECT
t.farm_id,
t.id,
t.name,
t.description
FROM
tree t
WHERE
t.farm_id = :farmid
AND ( lower(t.name) LIKE '%'
|| lower(:filter)
|| '%'
OR lower(t.description) LIKE '%'
|| lower(:filter)
|| '%'
OR ( t.id IN (
SELECT DISTINCT
tt.tree_id
FROM
tree_tag tt, tag ttag
WHERE
tt.tag_id = ttag.id
AND lower(ttag.name) LIKE '%'
|| lower(:filter)
|| '%'
) ) );
SELECT
COUNT(*)
FROM
tree t
WHERE
t.farm_id = :farmid
AND ( lower(t.name) LIKE '%'
|| lower(:filter)
|| '%'
OR lower(t.description) LIKE '%'
|| lower(:filter)
|| '%'
OR ( t.id IN (
SELECT DISTINCT
tt.tree_id
FROM
tree_tag tt, tag ttag
WHERE
tt.tag_id = ttag.id
AND lower(ttag.name) LIKE '%'
|| lower(:filter)
|| '%'
) ) );
JPA -
void buildQuery(EntityManager em, String farmId, String filter) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tree> cq = cb.createQuery(Tree.class);
Root<Tree> tree = cq.from(Tree.class);
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(tree.get("farm").get("id"), farmId));
Predicate namePredicate = cb.like(tree.get(Tree_.name), "%"+filter+"%");
Predicate descriptionPredicate = cb.like(tree.get(Tree_.description), "%"+filter+"%");
Subquery<String> subQuery = cq.subquery(String.class);
Root<TreeTag> treeTagRoot = subQuery.from(TreeTag.class);
Join<TreeTag, Tag> treeTagTagJoin = treeTagRoot.join(TreeTag_.tag);
List<Predicate> subPredicates = new ArrayList<>();
subPredicates.add(cb.equal(treeTagRoot.get(TreeTag_.tag).get(Tag_.id), treeTagTagJoin.get(Tag_.id)));
subPredicates.add(cb.like(treeTagTagJoin.get(Tag_.name), "%"+filter+"%"));
subQuery.select(treeTagRoot.get(Treetag_.tree).get(Tree_.id)).distinct(true).where(subPredicates.toArray(new Predicate[0]));
Predicate inSubQueryPredicate = tree.get(Tree_.id).in(subQuery);
predicates.add(cb.or(namePredicate, descriptionPredicate, inSubQueryPredicate));
cq = cq.where(predicates.toArray(new Predicate[0]));
cq = cq.orderBy(request.buildOrderBy(cb, tree));
TypedQuery<Tree> query = em.createQuery(cq);
List<Tree> trees = query.getResultList();
// for count - using the same query as above but replacing above 2 lines as
// cq = cq.select(cb.count(tree));
// TypedQuery<Long> query = em.createQuery(cq);
// int count = query.getSingleResult().intValue();
}
Entity Classes -
#Entity
#Table(name = "FARM"))
public class Farm {
#Id
#Column(name = "ID")
String id;
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
}
#Entity
#Table(name = "TAG", uniqueConstraints = #UniqueConstraint(columnNames = {"FARM_ID", "NAME"}))
public class Tag {
#Id
#Column(name = "ID")
String id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "FARM_ID", nullable = false, updatable = false)
Farm farm;
#Column(name = "NAME")
protected String name;
#Column(name = "DESCRIPTION")
private String description;
#OneToMany(mappedBy = "tag", fetch = FetchType.LAZY)
#CascadeOnDelete
private List<TreeTag> treeTagList = new ArrayList<>();
}
#MappedSuperclass
public abstract class ResourceTag {
#Id
#Column(name = "ID")
String id;
#ManyToOne
#JoinColumn(name = "TAG_ID", nullable = false)
protected Tag tag;
#Column(name = "VALUE")
protected String value;
}
#Entity
#Table(name = "TREE_TAG", uniqueConstraints = #UniqueConstraint(columnNames = {"TAG_ID", "TREE_ID"}))
public class TreeTag extends ResourceTag {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "TREE_ID", nullable = false)
private Tree tree;
}
#Entity
#Table(name="TREE",uniqueConstraints = #UniqueConstraint(columnNames = {"NAME”,"FARM_ID"}))
public class Tree {
#Id
#Column(name = "ID")
String id;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "FARM_ID", nullable = false)
Farm farm;
#Column(name= "NAME", nullable=false)
private String name;
#Column(name = "DESCRIPTION")
private String description;
#OneToMany(mappedBy = "tree", fetch = FetchType.LAZY)
#CascadeOnDelete
#BatchFetch(value=BatchFetchType.JOIN)
private List<TreeTag> treeTagList = new ArrayList<>();
}
How can I make this JPA code work for both the list and count? Thanks
I have the following table structure.
(The unique constraint is to avoid multiple 'details' to the same employee - I can't change the db structure).
https://i.ibb.co/r3pYQFj/fk.png
create table employee (
employee_id number(19),
salary number(10),
constraint pk_employee primary key (employee_id)
);
create table employee_details (
employee_details_id number(19),
employee_id number(19) not null,
address varchar2(256),
gender char(1),
constraint fk_employee foreign key (employee_id) references employee (employee_id),
constraint fk_employee_unq unique (employee_id)
);
Model class:
#Entity
#Table(name = "EMPLOYEE")
public class Employee implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "empgen")
#SequenceGenerator(name = "empgen", sequenceName = "SEQ_EMP", allocationSize = 1)
#Column(name = "EMPLOYEE_ID")
private Long id;
#OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="EMPLOYEE_ID")
private EmployeeDetail empDetail;
...
#Entity
#Table(name = "EMPLOYEE_DETAIL")
public class EmployeeDetail implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "empdetgen")
#SequenceGenerator(name = "empdetgen", sequenceName = "SEQ_EMP_DET", allocationSize = 1)
#Column(name = "EMPLOYEE_DETAILS_ID")
private Long id;
#Column(name = "EMPLOYEE_ID")
private Long employeeId;
...
I have a rest controller that receive a JSON like this:
{
"employee": {
"salary": 80000,
"empDetail": {
"adress": "ST EXAMPLE",
"gender": "M"
}
}
}
I'm trying to persist all the entities via hibernate (5.4.28) saving Employee as the first entity, then with its primary key, EmployeeDetails using it's parent primary key but I get this:
java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("DCC"."EMPLOYEE_DETAILS"."EMPLOYEE_ID")
Why it's trying to save the child before the parent?
How the the class should be mapped?
I guess it's because Hibernate thinks that by putting #JoinColumn on Employee.empDetail, EMPLOYEE_ID belongs to the employee_details table.
Try putting creating a property EmployeeDetail.employee and put #JoinColumn on that one. If you need a reference from Employee, use #OneToOne(mappedBy=...).
How to use #JoinColumn
Activate logging to see which statements are executed
I want to map an entity, which has a relationship with another table, but when mapping that relationship, it doesn't find the "Cardinality" column.
This is the code:
Entity elemento:
#Entity
#Table(name = "elemento")
#Inheritance(strategy=InheritanceType.JOINED)
#DiscriminatorColumn(name="clave", discriminatorType = DiscriminatorType.STRING, length=10)
public class Elemento implements Serializable, GenericInterface {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "clave", insertable = false)
private String clave;
#Column(name = "numero")
private String numero;
#Column(name = "nombre")
private String nombre;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "Proyectoid")
private Proyecto proyecto;
#Column(name = "descripcion")
private String descripcion;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "EstadoElementoid", referencedColumnName="id")
private EstadoElemento estadoElemento;
Entity actor:
#Entity
#Table(name = "actor")
#Inheritance(strategy=InheritanceType.JOINED)
#PrimaryKeyJoinColumn(name = "Elementoid", referencedColumnName = "id")
#DiscriminatorValue("ACT")
public class Actor extends Elemento implements Serializable, GenericInterface, ElementoInterface {
private static final long serialVersionUID = 1L;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "Cardinalidadid", referencedColumnName = "id")
private Cardinalidad cardinalidad;
This is the description of the tables:
TABLE ACTOR:
| actor | CREATE TABLE `actor` (
`otraCardinalidad` varchar(45) DEFAULT NULL,
`Elementoid` int(11) NOT NULL,
`Cardinalidadid` int(11) NOT NULL,
PRIMARY KEY (`Elementoid`),
KEY `FKActor872913` (`Cardinalidadid`),
KEY `FKActor148309` (`Elementoid`),
CONSTRAINT `FKActor148309` FOREIGN KEY (`Elementoid`) REFERENCES
`elemento` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FKActor872913` FOREIGN KEY (`Cardinalidadid`) REFERENCES
`cardinalidad` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
TABLE CARDINALIDAD
| cardinalidad | CREATE TABLE `cardinalidad` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nombre` varchar(10) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueCardinalidad` (`nombre`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1 |
This error appears
02:57:43.663 [qtp1469821799-35] DEBUG
com.mchange.v2.c3p0.impl.NewPooledConnection -
com.mchange.v2.c3p0.impl.NewPooledConnection#48c2c8ce handling a
throwable. java.sql.SQLException: Column 'cardinalidadid' not found.
I want to create JPA query for configuring multiple Terminals to one Contract:
CREATE TABLE `contracts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
) ENGINE=InnoDB;
CREATE TABLE `contracts_terminals` (
`terminal_id` int(11) DEFAULT NULL,
`contract_id` int(11) DEFAULT NULL,
) ENGINE=InnoDB;
CREATE TABLE `terminals` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB;
How I can create JPA query which uses table contracts_terminals to assign multiple terminals to one contract?
I use latest MariaDB.
Entities:
Contracts:
#Entity
#Table(name = "contracts")
public class Contracts implements Serializable {
private static final long serialVersionUID = 3873648042962238717L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(length = 255)
private String name;
......
}
Terminals:
#Entity
#Table(name = "terminals")
public class Terminals implements Serializable {
private static final long serialVersionUID = 5288308199642977991L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, updatable = false, nullable = false, length = 3)
private int id;
#Column(length = 255)
private String name;
....
}
ContractTerminals:
#Entity
#Table(name = "contract_terminals")
public class ContractTerminals implements Serializable {
private static final long serialVersionUID = 1191148141983861602L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(length = 4)
private Integer terminal_id;
#Column(length = 4)
private Integer contract_id;
....
}
I have this MariaDB table which I would like to use for bar chart:
CREATE TABLE `payment_transaction_daily_facts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date DEFAULT NULL,
`year` int(11) DEFAULT NULL,
`month` int(11) DEFAULT NULL,
`week` int(11) DEFAULT NULL,
`day` int(11) DEFAULT NULL,
`volume` int(11) DEFAULT NULL,
`count` int(11) DEFAULT NULL,
'created_at' date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
In my example SQL query I have single column for Date. How I can calculate the volumes per day for last 10 days when I have split date, year, month, week and day into different columns?
The final result should be for example:
Date | Amount| Number of transactions per day |
11-11-2018 | 30 | 3 |
11-12-2018 | 230 | 13 |
I tried this:
SELECT SUM(amount) AS sum_volume, COUNT(*) AS sum_Transactions
WHERE (created_at BETWEEN '2018-11-07' AND '2018-11-08')
GROUP BY DATE(created_at)
I want to return the generated data using DTO:
public class DashboardDTO {
private Date date;
private int sum_volume;
private int sum_Transactions;
... getters and setters
}
Rest controller:
#RestController
#RequestMapping("/dashboard")
public class DashboardController {
private static final Logger LOG = LoggerFactory.getLogger(DashboardController.class);
#Autowired
private DashboardRepository dashboardRepository;
#Autowired
private PaymentTransactionsDailyFactsMapper mapper;
#GetMapping("/volumes")
public ResponseEntity<List<DashboardDTO>> getProcessingVolumes(#PathVariable String start_date, #PathVariable String end_date) {
List<DashboardDTO> list = StreamSupport.stream(dashboardRepository.findPaymentTransactionsDailyFacts(start_date, end_date).spliterator(), false)
.map(mapper::toDTO)
.collect(Collectors.toList());
return ResponseEntity.ok(list);
}
}
JPA query:
public List<PaymentTransactionsDailyFacts> findPaymentTransactionsDailyFacts(LocalDateTime start_date, LocalDateTime end_date) {
String hql = "SELECT SUM(amount) AS sum_volume, COUNT(*) AS sum_Transactions " +
" WHERE (created_at BETWEEN :start_date AND :end_date )" +
" GROUP BY DATE(created_at)";
TypedQuery<PaymentTransactionsDailyFacts> query = entityManager.createQuery(hql,
PaymentTransactionsDailyFacts.class).setParameter("start_date", start_date).setParameter("end_date", end_date);
List<PaymentTransactionsDailyFacts> data = query.getResultList();
return data;
}
How should I implement the query properly?
When I receive start_date and end_date as String from Angular how should I convert it into LocaDateTime?
Well, as I commented, time is a dimension in a data warehouse star schema, and I guess period is as well. So you should have two dimension tables, a TimeDim for LocalDate, and a PeriodDim for Period. Then you should have a Fact with the an embeddedId made up of the various dimensions in your schema. Then you would have facts for 1 day periods and facts for 10 day periods. If you insisted on summing facts you have the issue that JPA cannot do a <= or >= comparison against composite keys. Since you are only summing 10 days you could use a in clause to select 10 keys, but again, you should have facts for the periods you need.
#Entity
public class TimeDim {
#Id
private LocalDate localDate;
#Entity
public class PeriodDim {
#Id
private Period period;
// need this too
#Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {
#Override
public Date convertToDatabaseColumn(LocalDate locDate) {
return (locDate == null ? null : Date.valueOf(locDate));
}
#Override
public LocalDate convertToEntityAttribute(Date sqlDate) {
return (sqlDate == null ? null : sqlDate.toLocalDate());
}
}
#SuppressWarnings("serial")
#Embeddable
public class DimKey implements Serializable {
private LocalDate localDate;
private Period period;
#Entity
public class Fact {
#EmbeddedId
private DimKey dimKey = new DimKey();
private long amount;
And for example:
tx.begin();
TimeDim td10 = new TimeDim();
td10.setLocalDate(LocalDate.now().minusDays(5));
em.persist(td10);
TimeDim td5 = new TimeDim();
td5.setLocalDate(LocalDate.now().minusDays(10));
em.persist(td5);
PeriodDim pd5 = new PeriodDim();
pd5.setPeriod(Period.ofDays(5));
em.persist(pd5);
PeriodDim pd10 = new PeriodDim();
pd10.setPeriod(Period.ofDays(10));
em.persist(pd10);
Fact f10 = new Fact();
f10.getDimKey().setLocalDate(td10.getLocalDate());
f10.getDimKey().setPeriod(pd10.getPeriod());
f10.setAmount(100);
em.persist(f10);
Fact f51 = new Fact();
f51.getDimKey().setLocalDate(td10.getLocalDate());
f51.getDimKey().setPeriod(pd5.getPeriod());
f51.setAmount(50);
em.persist(f51);
Fact f52 = new Fact();
f52.getDimKey().setLocalDate(td5.getLocalDate());
f52.getDimKey().setPeriod(pd5.getPeriod());
f52.setAmount(50);
em.persist(f52);
tx.commit();
em.clear();
DimKey dk = new DimKey();
dk.setLocalDate(td10.getLocalDate());
dk.setPeriod(pd10.getPeriod());
Fact f = em.createQuery("select f from Fact f where f.dimKey = :dimKey", Fact.class)
.setParameter("dimKey", dk)
.getSingleResult();
System.out.println("From 10 day period: " + f.getAmount());
DimKey dk1 = new DimKey();
dk1.setLocalDate(td10.getLocalDate());
dk1.setPeriod(pd5.getPeriod());
DimKey dk2 = new DimKey();
dk2.setLocalDate(td5.getLocalDate());
dk2.setPeriod(pd5.getPeriod());
Long sum = em.createQuery("select sum(f.amount) from Fact f where f.dimKey in (:dimKey1 , :dimKey2)", Long.class)
.setParameter("dimKey1", dk1)
.setParameter("dimKey2", dk2)
.getSingleResult();
System.out.println("From 2*5 day period: " + sum);