how can i use jdbcTemplate for Date field dynamically? - java

how can i map following query in jdbctemplate
select count(*),trim(rdate)
from man
where r='AGREE' and
rdate LIKE date '2016-04-12'
group by trim(rdate);
where i am sending date argument dynamically and this query/method should return type int only.
query in jdbc template should be like
select count(*),trim(rdate)
from man
where r='AGREE' and
rdate LIKE date ?
group by trim(rdate);
where i replace date with ? and it should return type int only
can anyone help me for this?

Related

Hibernate method name to SQL query - OR statement

My entity has 2 dates - startingDate, buildingDate.
I need a query that finds all rows with either date between 2 parameter dates.
public List<Factory> findByStartingDateBetweenOrBuildingDateBetween(LocalDate from, Localdate to);
Writing such method gives me an error and I have to extend parameters by another 2 dates.
public List<Factory> findByStartingDateBetweenOrBuildingDateBetween(LocalDate from, Localdate to, LocalDate fromDate, LocalDate toDate);
Is there a way to write such method that only takes 2 parameters and assigns them to both dates in the query?
I hope the below method will works for you.
public List<Factory> findAllByStartingDateLessThanEqualAndBuildingDateGreaterThanEqual(LocalDate startingDate, LocalDate buildingDate);
Use below native query above the method, Hope this will works for you.
select * from factory where (starting_date>=:from and starting_date<=:to) or (building_date>=:from and building_date<=:to);
SELECT * FROM Table_name WHERE start_date >=:from AND start_date<=:to
by using this query you can get the list of data in between this date
try this-
native query method -
#Query(value = "select * from factory where (starting_date>= ?1 AND starting_date<= ?2) OR (building_date>= ?1 and building_date<= ?2)", nativeQuery = true)
List<Factory> findFactoryByDate(LocalDate from, Localdate to);
JPA QUERY METHOD
public List<Factory> findByStartingDateOrBuildingDateBetween(LocalDate from, Localdate to);
Set<Factory> findAllByStartingDateBetween(Date Start, Date End);

JPA Query for fomat Date

In Data base , createdDt is storing formated like:
15-01-20 10:43:20.394000000 AM
I am passing "created" as dd-mm-yyyy
I want to take the matching date from the table(without comparing time)
#Query("SELECT p FROM ABC p WHERE ( COALESCE(:created) is null or p.createdDt = :created) order by p.createdDt desc")
List<ABC> filterABC(#Param("created") Date created);
How to parse the date within query ?
You could try to use native query using specific DBMS stuff to extract date part.
#Query(value = "SELECT * from ABC where DATE_FORMAT(createdDt, '%d-%m-%Y') = ?1", nativeQuery = true)
List<ABC> filterABC(Date created);
DATE_FORMAT is MySQL specific function. Use the appropriate date function in accordance with your DBMS

Spring Data: multiple IN's inside a query

I have the following method inside my spring jpa data interface:
List<TransactRepViewModel> findByClientIdInAndClDateBetween(List<String> clientIdList, Date startDate, Date endDate)
The problem is that I get this error due to my clientIdList having about 5000-20000 String objects inside:
ORA-01795: maximum number of expressions in a list is 1000
Is there a way to use multiple IN's inside a spring-data query and split up my list to avoid the error?
Update:
Ths is how I get my client object list:
List<ClieTabModel> clieTabModelList = clieTabModelRepository.findByCompanyId(companyViewModel.getId());
This is how I get the list of client Id's:
List<String> clientIdList = new ArrayList <>();
for (ClieTabModel clieTabModel : clieTabModelList) {
clientIdList.add(clieTabModel.getClientId());
}
You can use the following query:
#Query("select u from User u where u.id in :clientIds and :startDate=? and endDate= :endDate")
List<TransactRepViewModel> findByClientIdInAndClDateBetween(Set<String> clientIds, Date startDate, Date endDate)
As I see your ER model should look like this:
Transact >--- Client >--- Company.
So, in this case you can write follow query:
List<TransactRepViewModel> findByClientCompanyIdAndClDateBetween(String companyId, Date startDate, Date endDate)

Extract Year from date field using jpql and jpa

I want to extract the year part from a row in the database in order to compare it with a value.
Here's my function
public List<Dossier> getAllDossierParAn() {
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int strI = calendar.get(Calendar.YEAR);
TypedQuery<Dossier> query;
query = em.createQuery("SELECT d FROM DOSSIER d WHERE EXTRACT(YEAR ,d.dateCreation)=2015", Dossier.class);
System.out.println(strI);
return query.getResultList();
}
I get always
An exception occurred while creating a query in EntityManager:
Exception Description: Problem compiling [SELECT d FROM DOSSIER d WHERE EXTRACT(YEAR FROM d.dateCreation)=2015]. [14, 21] The abstract schema type 'DOSSIER' is unknown. [48, 62] The state field path 'd.dateCreation' cannot be resolved to a valid type.
I test it directly in the database and it works
select * from dossier where extract(year from date_creation)=2015
I'm using jpa and ejb and jdeveloper as IDE.
First, the main problem with your query is what the error message say:
The abstract schema type 'DOSSIER' is unknown
Since JPA is mapping your POJOs as entities, their names are case sensitive. Your query should be:
SELECT d FROM Dossier d WHERE ...
Also, regarding the problem you mentioned, the EXTRACT function is only supported by EclipseLink, as far as I know. By the error message, I think this is your JPA implementation, but if it's not, there are two options:
If you're using Hibernate, it has built in functions for retrieving date parts, such as YEAR(date), MONTH(date), DAY(date), HOUR(date), MINUTE(date) and SECOND(date).
For any other JPA implementation, or if you want to keep it JPQL compliant, you can workaround with SUBSTRING: SUBSTRING(d.dateCreation, 1, 4). Note the first position of a string is denoted by 1;
Hope it helps
"Directly in the database" is called SQL.
createQuery takes in JPQL not SQL, and YEAR / EXTRACT are invalid keywords (though YEAR, but not EXTRACT, is supported by some JPA providers). Any decent JPA docs would spell that out.
thank you guys i solved the problem:
first i got the current year than format it to int than to String in order to do the comparaison and substract it here's my code it work fine:
public List<Dossier> getAllDossierParAn() {
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int strI = calendar.get(Calendar.YEAR);
String strInt =Integer.toString(strI);
String nvlstri= strInt.substring(2, 4);
TypedQuery<Dossier> query;
query = em.createQuery("SELECT d FROM Dossier d WHERE SUBSTRING(d.dateCreation, 7, 2) = :vr", Dossier.class);
query.setParameter("vr",nvlstri);
System.out.println("l anne est " +strI);
System.out.println("la date formaté " +nvlstri);
return query.getResultList();
}
On eclipselink, the way that works for me was something like:
SELECT a.id, EXTRACT(WEEK CURRENT_DATE ) FROM Account a
This works on postgres and sql server at least but should work with other supported databases too.
From javadocs the syntax supported is :
extract_expression ::= EXTRACT(date_part_literal [FROM] scalar_expression)
The FROM seems to cause funny exceptions on sql server.

Compare timestamp date in Postgresql in java

I am using PostgreSQL database & JPA. Here is my user table
CREATE TABLE users
(
id integer NOT NULL DEFAULT nextval('userseq'::regclass),
firstname character varying(64) ,
middlename character varying(64),
lastname character varying(64),
birthdate timestamp with time zone,
)
Query query = em
.createQuery(
"SELECT users FROM Users users WHERE user.birthdate =:a")
.setParameter("a",18)
.setParameter("b",25);
query.getResultList();
I want get all user whose age in between 18-25. Please complete my above JPA query
Use Between operator, fix to user.birthdate to users.birthdate at first.
Calendar cal_1 = Calendar.getInstance();
cal_1.add(Calendar.YEAR, -18);
Date a = cal_1.getTime();
Calendar cal_2 = Calendar.getInstance();
cal_2.add(Calendar.YEAR, -25);
Date b = cal_2.getTime();
query.setParameter("a", a);
query.setParameter("b", b);
SELECT users FROM Users users WHERE users.eventsDate BETWEEN :a AND :b
Example : x BETWEEN :min AND :max. Reference here
JPQL is lacking in date operators. In SQL you'd write something like:
SELECT age(TIMESTAMPTZ '1999-01-01') BETWEEN INTERVAL '18' YEAR AND INTERVAL '25' YEAR;
but you can't do that in JPQL as far as I can tell. BETWEEN is supported in JPQL, so I'd convert the date parameters a and b to java.util.Date using java.util.Calendar, then use:
SELECT users FROM Users users WHERE user.birthdate BETWEEN :a AND :b

Categories

Resources