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.
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 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
Here are two queries that should be exactly the same except one is marked as native and the other is not. The first one works fine, but the second one fails with incompatible data type in conversion
#Transactional(readOnly = true)
#Query(value = "select startDate from TaskMetrics where startDate between :startDate and :endDate")
List<DateTime> findStartDateByStartDateBetween(#Param("startDate") DateTime startDate,
#Param("endDate") DateTime endDate);
This generates the query:
select taskmetric0_.startDate as col_0_0_ from TaskMetrics taskmetric0_ where taskmetric0_.startDate between ? and ?
With bindings
binding parameter [1] as [TIMESTAMP] - [2015-02-02 10:57:14.279]
binding parameter [2] as [TIMESTAMP] - [2015-02-04 10:57:14.281]
-
#Transactional(readOnly = true)
#Query(nativeQuery = true, value = "select startDate from TaskMetrics where startDate between :startDate and :endDate")
List<DateTime> findStartDateBetween(#Param("startDate") DateTime startDate,
#Param("endDate") DateTime endDate);
This generates the query:
select startDate from TaskMetrics where startDate between ? and ?
With one binding, which also seems a bit odd (especially why #2?):
binding parameter [2] as [VARBINARY] - [2015-02-04T10:57:14.315-05:00]
I'm using Hibernate 4.3.8.Final as my JPA 2.1 provider and Jadira Usertype 3.1.0.CR10 for JodaTime support.
Am I doing something wrong or is this a bug somewhere?
Bug opened here - https://jira.spring.io/browse/DATAJPA-671
Workaround for the bug:
public class MyDaoClass {
// Converter provided by joda time user type library
private TimestampColumnDateTimeMapper columnDateTimeMapper = new TimestampColumnDateTimeMapper();
#Override
public void doAction(MyObject myObject) {
Query q = getEntityManager().createNamedQuery("MyNativeNamedQuery");
q.setParameter("date", columnDateTimeMapper.toNonNullValue(myObject.getDate()), TemporalType.TIMESTAMP);
q.executeUpdate(); // or select
}
The second one is a nativeQuery as i know the will not work with joda DateTime. use Java.sql.Date instead.
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