JPA Query for fomat Date - java

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

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

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)

how to parse date n java to oracle/sql query?

I have a Query like
String query = "Select * from Orders where ordername = ? and orderDate > SYSDATE - 2 ";
i will pass **orderName** and lastDate from UI or some constant ("20-9-2016").
orderDate=SYSDATE - 2 --> instead of "2" i will send lastDate.
Is it correct? SYSDATE oracle function and "2" before constant. now "2" can be user input.
How to write a query in java
String query = "Select * from Orders where ordername = ? and orderDate > SYSDATE - ? ";
Is above query correct ? how to write query
public class CheckOrders extends MappingSqlQuery<Object>{
public PendingOrderExists() {
super(dataSource, queryConfig
.getProperty("query"));
super.declareParameter(new SqlParameter("ORDERNAME", Types.VARCHAR));
//orderdate ? how to declare parameter here
compile();
}
}
for sysdate-?
the ? parameter is to be set object of java.sql.Date class instead of java.util.Date class.
java.sql.Date inherits java.util.Date.
java.sql.Date(long time)
here long is number of milliseconds lapsed since jan1,1979.
GregorianCalendar gc=new GregorianCalendar(2000, 25, 2);
java.util.Date dt=gc.getTime();
long lg=dt.getTime();
java.sql.Date sqldt=new java.sql.Date(lg);
'
pass sqldt object in setDate() method of preparedstatement instance.
hope this works
alkaramansari1#gmail.com

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

HQL(hibernate) timestamp range match

I need to write a query to get an object between a range of time, currently the query looks like this:
Timestamp from = ...
Timestamp to = ...
getHibernateTemplate().find("from " + Person.class.getName() + " ml where ml.lastModifiedOn>="+from.toString()+" and m1.lastModifiedOn<=" + to.toString());
However, this doesnot work for obvious reasons. How can I format the timestamp to be acceptable by the query.
org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: 16 near line 1, column 123 [from Person ml where ml.lastModifiedOn>=2010-02-12 16:00:21.292 and m1.lastModifiedOn
You're missing single quotes in your current query. The following should work:
from Person ml where ml.lastModifiedOn
between '2010-02-12 16:00:21.292' and '2010-02-12 23:00:21.292'
Note that I don't know why you're not passing Date instances to the following query:
from Person ml where ml.lastModifiedOn between :from and :to
Are you using java.sql.Timestamp here? If yes, you shouldn't.
You can simply pass a long (from.getTime()) in the comparison, if it is represented as long in the DB.
Otherwise you can use these functiomns: second(...), minute(...), hour(...), day(...), month(...), and year(...)
How about something like this?
String sql = "from " + Person.class.getName() + " ml where ml.lastModifiedOn>= ? and m1.lastModifiedOn<= ?";
Date from = ...;
Date to = ...;
getHibernateTemplate().find(sql, new Object[] {from,to});
If you want to query for something between you can do the following:
public List findPerson() {
Date from = ...;
Date to = ...;
return entityManager.createQuery(
"SELECT p from Person p WHERE p.lastModifiedOn BETWEEN ?1 AND ?2")
.setParameter(1,from, TemporalType.DATE)
.setParameter(2,to, TemporalType.DATE).getResultList();
}
You might need to change TemporalType.DATE to whatever you are using

Categories

Resources