How represent a date in a JPA query, without using (typed) parameters?
If the date is really fixed (for example, 1 mar 1980), the code:
TypedQuery<MyEntity> q = em.createQuery("select myent from db.MyEntity myent where myent.theDate=?1", db.MyEntity.class).setParameter(1, d);
having set:
Date d = new Date(80, Calendar.MARCH, 1);
is quite verbose, isn't it? I would like to embed 1980/1/3 into my query.
UPDATE:
I modified the sample date to 1980/1/3, because 1980/1/1 as it was, was ambiguous.
IIRC you can use date literals in JPQL queries just like you do it in JDBC, so something like:
// d at the beginning means 'date'
{d 'yyyy-mm-dd'} i.e. {d '2009-11-05'}
// t at the beginning means 'time'
{t 'hh-mm-ss'} i.e. {t '12-45-52'}
// ts at the beginning means 'timestamp'; the part after dot is optional
{ts 'yyyy-mm-dd hh-mm-ss.f'} i.e. {ts '2009-11-05 12-45-52.325'}
should do the work (the curly braces and apostrophes are required).
I spent a couple days digging around on this. Seems the root of the problem is that the Hibernate generated grammar does not include support for temporal literals.
The JPA specification does include support for temporal literals but does not require persistence providers to translate from from the JPA syntax to the native syntax of the JDBC driver. From the JPA2 Spec 4.6.1:
"The JDBC escape syntax may be used for the specification of date, time, and timestamp literals. For example:
SELECT o
FROM Customer c JOIN c.orders o
WHERE c.name = 'Smith'
AND o.submissionDate < {d '2008-12-31'}
The portability of this syntax for date, time, and timestamp literals is dependent upon the JDBC driver in use. Persistence providers are not required to translate from this syntax into the native syntax of the database or driver."
It would be nice if Hibernate did provide support for date literals, but it seems the implementation for this is a little more involved that I'd suspected.
The functionality lacking here as far as my needs are concerned is that you cannot do a select coalesce(somePath, someDateLiteral) query. You can still do a where somePath=someDate. As long as they're mapped entities you can throw whatever you want in a where clause.
I used criteriaQuery for my querys, its just great. It looks like:
#Override
public List<Member> findAllByDimensionAtTime(Dimension selectedDimension,
Date selectedDate) {
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Member> criteriaQuery = criteriaBuilder
.createQuery(Member.class);
Root<Member> member = criteriaQuery.from(Member.class);
criteriaQuery
.select(member)
.where(criteriaBuilder.lessThanOrEqualTo(
member.get(Member_.validFrom), selectedDate),
criteriaBuilder.greaterThanOrEqualTo(
member.get(Member_.validTo), selectedDate),
criteriaBuilder.equal(
member.get(Member_.myDimensionId),
selectedDimension.getId())).distinct(true);
return em.createQuery(criteriaQuery).getResultList();
validFrom and validTo are date fields!
Edit: shorter Example (according to yours):
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<MyEntity> criteriaQuery = criteriaBuilder
.createQuery(MyEntity.class);
Root<MyEntity> entity= criteriaQuery.from(MyEntity.class);
criteriaQuery
.select(member)
.where(criteriaBuilder.equal(
entity.get(MyEntity_.theDate),
new Date(80, Calendar.MARCH, 1);)).distinct(true);
return em.createQuery(criteriaQuery).getResultList();
Related
I have a Java8 application using SpringBoot, which is pulling in Hibernate core 5.3.10 (connected to PostgreSQL 11). A simplified explanation: the application is maintaining a history of changes to a series of bespoke UserData records, containing two LocalDateTime columns for startDate and endDate, and a userId column (plus other columns).
The semantics of the application are that a history of changes to the UserData are maintained by the start_date and end_date contain no duplicates (respectively), and that any row where the endDate is null is the currently active record for a user. (Accordingly, a user may have no currently active record.)
It is a simple matter to retrieve all of the active rows, and this is working well.
However, I have a requirement to retrieve the latest row for all users irrespective of whether the row is active or not.
One way to achieve this outcome using SQL is with a query something like the following:
select ud1.* from user_data ud1
where ud1.start_date = (select max(ud2.start_date) from user_data ud2
where ud2.user_id = ud1.user_id);
I have been attempting to write a CriteriaQuery to replicate the SQL, but I have run into a data type problem with the CriteriaBuilder.max method. The max method is complaining that it will only accept a type Number column. The code looks like this:
final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
final CriteriaQuery<UserDate> criteriaQuery = builder.createQuery(UserData.class);
final Root<UserData> ud1 = criteriaQuery.from(UserData.class);
final Subquery<LocalDateTime> maxUserDataStartDate = criteriaQuery.subquery(LocalDateTime.class);
final Root<UserData> ud2 = maxUserDataStartDate.from(UserData.class);
maxUserDataStartDate.select(builder.max(ud2.get("startDate"));
// ...
The problem is with the last line, where it complains that ud2.get("startDate") is not an extension of type Number - which is true, of course.
Does anybody know how to fix this situation? Especially, does anybody have an example they can share that does what I'm after?
You can do order by start_date desc and get top 1
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<UserData> criteriaQuery = builder.createQuery(UserData.class);
Root<UserData> ud = criteriaQuery.from(UserData.class);
criteriaQuery.orderBy(builder.desc(ud.get("startDate")));
entityManager.createQuery(criteriaQuery).getFirstResult();
I'm trying to group entities by date intervals using JPA's Criteria API. I use this way of querying for entities as this is a part of the service that serves API requests which may ask for any field of any entity, including sorting, filtering, grouping and aggregations. Everything works fine except for grouping by date fields. My underlying DBMS i PostgreSQL.
To give a minimal example, here's my entity class:
#Entity
#Table(name = "receipts")
public class DbReceipt {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Date sellDate;
// Many other fields
}
This example discusses grouping my "month" interval (therefore grouping by year+month), but in the end I'm looking for a solution that would let me group by any interval, such as "year", "day" or "minutes".
What I'm trying to achieve is the following query, but using Criteria API:
SELECT TO_CHAR(sell_date, 'YYYY-MM') AS alias1 FROM receipts GROUP BY alias1;
My attempt to do so is this:
#Service
public class ReceiptServiceImpl extends ReceiptService {
#Autowired
private EntityManager em;
#Override
public void test() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Object[]> query = cb.createQuery(Object[].class);
Root<?> root = query.from(DbReceipt.class);
Expression<?> expr = cb.function("to_char", String.class, root.get("sellDate"), cb.literal("YYYY-MM"));
query.groupBy(expr);
query.multiselect(expr);
TypedQuery<Object[]> typedQuery = em.createQuery(query);
List<Object[]> resultList = typedQuery.getResultList();
}
}
The reason I use to_char function and not MONTH and similar is that I need entities like 2019-05 and 2020-05 to not be grouped together. I also narrow this example down to only year and month to keep things short, but the goal is to group by any date interval.
The code above creates the following query (SQL logging enabled) which results in an error:
Hibernate: select to_char(dbreceipt0_.sell_date, ?) as col_0_0_ from receipts dbreceipt0_ group by to_char(dbreceipt0_.sell_date, ?)
24-05-2020 12:16:30.071 [http-nio-1234-exec-5] WARN o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions - SQL Error: 0, SQLState: 42803
24-05-2020 12:16:30.071 [http-nio-1234-exec-5] ERROR o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions - ERROR: column "dbreceipt0_.sell_date" must appear in the GROUP BY clause or be used in an aggregate function
Position: 16
which to me is caused by the fact that the whole expression is put into the 'group by' part of the query, rather than just an alias. Now, I've tried to assign an alias to the expression (which returns Selection<T> and groupBy accepts expressions, therefore I can only really use that in the multiselect), but that didn't affect how the query is performed - nothing changed.
How do I achieve grouping by year and month as described above using Criteria API? Maybe there's a different way other than using to_char? Maybe there's a way to give an alias to the groupBy method that would cause it to group by an alias instead of the whole expression?
I think it's a bug in PostgreSQL (the error comes from there, not from Hibernate). I have tried a slightly modified version of your code with EclipseLink + Derby and works perfectly.
Note that I had to use numbers instead of strings because Derby DB doesn't have an equivalent of TO_CHAR function.
Expression<Integer> year = cb.function("YEAR", Integer.class, root.get("sellDate"));
Expression<Integer> month = cb.function("MONTH", Integer.class, root.get("sellDate"));
Expression<Integer> expr = cb.sum(month, cb.prod(12, year));
query.groupBy(expr);
query.multiselect(expr);
This returns the following SQL:
SELECT (MONTH(MY_DATE) + (12 * YEAR(MY_DATE)))
FROM MY_DATE_TABLE
GROUP BY (MONTH(MY_DATE) + (12 * YEAR(MY_DATE)))
Note that there are no portable solutions for manipulating dates in JPA criteria queries. If the number of groups to be queried simultaneously is not too high I'd go with a more practical approach where you find the dates in Java and pass them as literals to the query builder.
Another workaround is to query with a groupBy(root.get("sellDate")) and then aggregate the results in Java according to the desired time period.
Post Scriptum: I don't think it's relevant, however I modified the query's return type from Object[] to Object.
Is it possible (and if so how) to create a criteria query that results in a tuple or array of which some elements are collections from a collection valued property?
Given an entity Dummy which has a List<SubEntities> with name subs
class Dummy {
String name;
List<SubEntity> subs;
}
class SubEntity {
// some attributes
}
I want a criteria API query which results in something with the structure
Tuple>
An Array instead of a Tuple would be fine, same for an Array or similar for List.
I tried the following:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Object[]> q = cb.createQuery(Object[].class);
Root<DummyEntityWithCollection> root = q.from(DummyEntityWithCollection.class);
Join<Object, Object> subs = root.join("subs");
q.select(cb.array(root.get("name"), subs));
List<Object[]> list = em.createQuery(q).getResultList();
But the Object[]s contained in list have as the second element SubEntitys instead of List<SubEntity>.
This one fails in the same way:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> q = cb.createTupleQuery();
Root<DummyEntityWithCollection> root = q.from(DummyEntityWithCollection.class);
Join<Object, Object> subs = root.join("subs");
q.multiselect(root.get("name"), subs);
List<Tuple> list = em.createQuery(q).getResultList();
This variant
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Object[]> q = cb.createQuery(Object[].class);
Root<DummyEntityWithCollection> root = q.from(DummyEntityWithCollection.class);
q.select(cb.array(root.get("name"), root.get("subs")));
List<Object[]> list = em.createQuery(q).getResultList();
Doesn't work at all and results in an invalid SQL statement with a single . as one select column (at least for Hibernate and HSQLDB).
The question How can I retrieve a collection property using criteria Api seems to indicate that it is not possible but it is based on Hibernate and I would like to get a JPA based answer. Especially an answer pointing out the section of the JPA spec that makes it clear that this is not possible would be appreciated.
JPQL defines the select clause in section 4.8 as
select_clause ::= SELECT [DISTINCT] select_item {, select_item}*
select_item ::= select_expression [[AS] result_variable]
select_expression ::= single_valued_path_expression | scalar_expression | aggregate_expression | identification_variable | OBJECT(identification_variable) | constructor_expression
so you can see that multi-valued expressions are not selectable in JPQL.
Criteria is simply a way to create a query using an API and objects. See JPA spec chapter 6.1:
The semantics of criteria queries are designed to reflect those of Java Persistence query
language queries.
So it's reasonable to assume the same constraint applies to the Criteria API.
Now I am using JPA to access database. I want to get the comments in the specific courses and specific lessons, so the sql would like this:
select * from comment where (commentType, commentId) in (("course", "1"), ("lesson", 2))
I use annotation #Query like this:
#Query("select c from Comment c where (c.commentType, c.commentId) in :attaches")
Page<Comment> findByAttachIn(#Param("attaches") List<String[]> attaches, Pageable pageable);
But finally I got the sql like this:
select * from comment where (commentType, commentId) in (?)
JPA can not translate the array from jql to sql. What shall I do?
An IN expression allows only a single-valued path expressions, so you can't do (commentType, commentId) in in a JPQL query.
JPQL BNF documentation is very clear for the IN part
in_expression ::= {state_field_path_expression | type_discriminator} [NOT] IN { ( in_item {, in_item}* ) | (subquery) | collection_valued_input_parameter }
in_item ::= literal | single_valued_input_parameter
Consequently it can be concluded that you can't do that in JPQL. What you can do is do it manually in the WHERE clause ...
... WHERE (commentType = :type1 AND commentId = :id1) OR
(commentType = :type2 AND commentId = :id2) OR
...
long winded, but gets the answer, and complies with JPQL BNF notation. How you convert standard JPQL into some Spring syntax is left as an exercise to those familiar with that non-standard part
I am trying to use the Criteria API instead of constructing queries as JPQL Strings as the Criteria API seems much better suited for this. However, I am having a few problems understanding how to construct the two following statements.
SELECT e
FROM Subject e
WHERE e.company = :c1
OR e.company = :c2
OR e.company = :c3
In this case I need to iterate over an unknown number of values (c1, c2, c3 etc.) to match to the same attribute.
SELECT e
FROM Subject e
WHERE e.company
LIKE :c1
OR e.account
LIKE :c1
OR e.email
LIKE :c1
In this case I need to pass in a single value (c1) and have a 'LIKE' comparison done on a specific range of attributes.
My current pattern looks something like this:
// Criteria
CriteriaBuilder builder = subjectDAO.criteriaBuilder();
CriteriaQuery<Subject> query = builder.createQuery(Subject.class);
// Root
Root<Subject> subject = query.from(Subject.class);
List<Predicate> predicates = new ArrayList();
for (String property : map.keySet()) {
String value = (String) coreFilter.get(map);
predicates.add(????? This is where I come unstuck ?????);
}
// pass all the predicates into the query
query.where(predicates.toArray(new Predicate[predicates.size()]));
NB. I don't have any problems constructing the Query object or specifying the Root or Joins. I am just having problems with the specificity of the above queries. For the sake of clarity just assume that all the attributes are String and don't require any joins.
The expression CriteriaQuery<T> where(Predicate... restrictions), as you can see in the javadoc,
Modify the query to restrict the query result according to the conjunction of the specified restriction predicates.
So, it makes the conjunction of the predicates in the list, i.e. it concatenates them with AND expressions. In order to concatenate them with OR expression, simply use CriteriaBuilder#or(Predicate... restrictions)
query.where(builder.or(predicates.toArray(new Predicate[] {})));