I am trying to pull information from a table where the current date is between the first and last day of any given month.
I am getting a runtime error "Errors in named queries: Department.byDate"
I am providing you with what code I think could be causing the problem, if any additional code is needed please let me know in a comment.
My named query which looks like this:
#NamedQuery(name="Department.byDate", query="select * from department where date >= :first AND date <= :last")
I am using this named query in my DAO in a method which looks like this:
public List<Department> getRecords(Date dateFirst, Date dateLast){
Session session= sessionFactory.openSession();
session.beginTransaction();
Query query = session.getNamedQuery("Department.byDate");
query.setDate("first", dateFirst);
query.setDate("last", dateLast);
List<Department> depList = (List<Department>)query.list();
session.getTransaction().commit();
session.close();
return depList;
}
My method of getting that first and last days of the months looks like this:
Calendar first = Calendar.getInstance();
first.set(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
Date dateFirst = first.getTime();
Calendar last = Calendar.getInstance();
first.set(Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
Date dateLast = last.getTime();
In HQL/JPQL you are working with entities and their properties, thus * character has no meaning.
HQL/JPQL class and property names are case sensitive.
You should write your query the following way:
select d from Department d where d.date >= :first AND d.date <= :last
Related
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)
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.
I want to retrieve through Hibernate via Criteria the instances which in their date column have the current date.
1) So in MySQL DB via MySQL_Workbench I inserted an instance writing in the current date '2015-07-25'.
2) My java code looks like this :
Date date = new Date();
factory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
Criteria cr = session.createCriteria(Logger.class);
//the following date-like cr. fails
cr.add(Restrictions.eq("RunDate",date));
//this cr. runs fine alone retreiving the requested instances
cr.add(Restrictions.like("Name", "John"));
//The following work fine
cr.setProjection(Projections.sum("Contacts"));
long resultCount = (long)cr.uniqueResult();
System.out.println(resultCount);
...
When running with the date criteria I have a null pointer exception.I tried also cr.like,cr.ge ... same results.
What do you have as a value in your database?
if your date in your DB has time value as well and you only want to compare with the current day, you should do basically the following:
WHERE RunDate >= '2015-07-25 00:00:00' AND RunDate <= '2015-07-25 23:59:59'
like that only in an equivalent to the Criteria API
regards
Good afternoon , I need to filter a query by date, the date is defined in the database as:
y: m: d.
It 's performed with sqlnativo in hibernate but it returns null.
anyone can help me , also if someone can explain me how to handle criteria with dates, since I do not find any clear example
Query query = session.createSQLQuery("Select id,fecha,total,idEnvio FROM VENTA_CABECERA vc WHERE date(fecha) = :fec" ).addEntity(HeadSale.class);
query.setParameter("fec", date);
return query.list();
It can also be the between clause , but honestly I can not make it work. would be grateful to give me a solution.
regards
change the format of "fec" parameter as y: m: d and remove date function inside query
DateFormat df;
df= new SimpleDateFormat("y: m: d");
String dt= sdf.format(date);
Query query = session.createSQLQuery
("Select id,fecha,total,idEnvio FROM VENTA_CABECERA vc WHERE fecha = :fec" )
.addEntity(HeadSale.class);
query.setParameter("fec", dt);
return query.list();
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