I have a field in SSMS which is of type nvarchar. It has date and time stored in it . I want to retrieve records which is before a date using criteria_builder. I am able to retrieve it using SQL. The Sql is given below:
SELECT CONVERT(DateTime,f.field_values,103) as DueDate
FROM TableA a
JOIN TableB p ON a.id = p.activity_id
JOIN TableC s ON p.id = s.package_id
JOIN TableD f ON s.id = f.package_section_id
WHERE a.code like '%sass%' and f.field_name='Due_Date'
However when i try to use Hibernate criteria:
I get
Conversion failed when converting date and/or time from character string.
This occurs as I m not using the SQL Convert function. I have searched a lot online but unable to find how can i use CONVERT in Hibernate criteria. Hibernate predicate I am using is:
Predicate fieldPredicates = cb.and(cb.equal(packageFieldJoin.get(TableB_.fieldName), "Due_Date"),
cb.lessThan(packageFieldJoin.get(TableB_.fieldValuesData)), sdf1.parse(CLOSE_DUE_BEFORE)))
In Hibernate 3, is there a way to do the equivalent of the following MySQL limit in HQL?
select * from a_table order by a_table_column desc limit 0, 20;
I don't want to use setMaxResults if possible. This definitely was possible in the older version of Hibernate/HQL, but it seems to have disappeared.
This was posted on the Hibernate forum a few years back when asked about why this worked in Hibernate 2 but not in Hibernate 3:
Limit was never a supported clause
in HQL. You are meant to use
setMaxResults().
So if it worked in Hibernate 2, it seems that was by coincidence, rather than by design. I think this was because the Hibernate 2 HQL parser would replace the bits of the query that it recognised as HQL, and leave the rest as it was, so you could sneak in some native SQL. Hibernate 3, however, has a proper AST HQL Parser, and it's a lot less forgiving.
I think Query.setMaxResults() really is your only option.
// SQL: SELECT * FROM table LIMIT start, maxRows;
Query q = session.createQuery("FROM table");
q.setFirstResult(start);
q.setMaxResults(maxRows);
If you don't want to use setMaxResults() on the Query object then you could always revert back to using normal SQL.
The setFirstResult and setMaxResults Query methods
For a JPA and Hibernate Query, the setFirstResult method is the equivalent of OFFSET, and the setMaxResults method is the equivalent of LIMIT:
List<Post> posts = entityManager.createQuery("""
select p
from Post p
order by p.createdOn
""")
.setFirstResult(10)
.setMaxResults(10)
.getResultList();
The LimitHandler abstraction
The Hibernate LimitHandler defines the database-specific pagination logic, and as illustrated by the following diagram, Hibernate supports many database-specific pagination options:
Now, depending on the underlying relational database system you are using, the above JPQL query will use the proper pagination syntax.
MySQL
SELECT p.id AS id1_0_,
p.created_on AS created_2_0_,
p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?, ?
PostgreSQL
SELECT p.id AS id1_0_,
p.created_on AS created_2_0_,
p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?
SQL Server
SELECT p.id AS id1_0_,
p.created_on AS created_on2_0_,
p.title AS title3_0_
FROM post p
ORDER BY p.created_on
OFFSET ? ROWS
FETCH NEXT ? ROWS ONLY
Oracle
SELECT *
FROM (
SELECT
row_.*, rownum rownum_
FROM (
SELECT
p.id AS id1_0_,
p.created_on AS created_on2_0_,
p.title AS title3_0_
FROM post p
ORDER BY p.created_on
) row_
WHERE rownum <= ?
)
WHERE rownum_ > ?
The advantage of using setFirstResult and setMaxResults is that Hibernate can generate the database-specific pagination syntax for any supported relational databases.
And, you are not limited to JPQL queries only. You can use the setFirstResult and setMaxResults method seven for native SQL queries.
Native SQL queries
You don't have to hardcode the database-specific pagination when using native SQL queries. Hibernate can add that to your queries.
So, if you're executing this SQL query on PostgreSQL:
List<Tuple> posts = entityManager.createNativeQuery(
SELECT
p.id AS id,
p.title AS title
from post p
ORDER BY p.created_on
""", Tuple.class)
.setFirstResult(10)
.setMaxResults(10)
.getResultList();
Hibernate will transform it as follows:
SELECT p.id AS id,
p.title AS title
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?
Cool, right?
Beyond SQL-based pagination
Pagination is good when you can index the filtering and sorting criteria. If your pagination requirements imply dynamic filtering, it's a much better approach to use an inverted-index solution, like ElasticSearch.
If you don't want to use setMaxResults, you can also use Query.scroll instead of list, and fetch the rows you desire. Useful for paging for instance.
You can easily use pagination for this.
#QueryHints({ #QueryHint(name = "org.hibernate.cacheable", value = "true") })
#Query("select * from a_table order by a_table_column desc")
List<String> getStringValue(Pageable pageable);
you have to pass new PageRequest(0, 1)to fetch records and from the list fetch the first record.
You need to write a native query, refer this.
#Query(value =
"SELECT * FROM user_metric UM WHERE UM.user_id = :userId AND UM.metric_id = :metricId LIMIT :limit", nativeQuery = true)
List<UserMetricValue> findTopNByUserIdAndMetricId(
#Param("userId") String userId, #Param("metricId") Long metricId,
#Param("limit") int limit);
String hql = "select userName from AccountInfo order by points desc 5";
This worked for me without using setmaxResults();
Just provide the max value in the last (in this case 5) without using the keyword limit.
:P
My observation is that even you have limit in the HQL (hibernate 3.x), it will be either causing parsing error or just ignored. (if you have order by + desc/asc before limit, it will be ignored, if you don't have desc/asc before limit, it will cause parsing error)
If can manage a limit in this mode
public List<ExampleModel> listExampleModel() {
return listExampleModel(null, null);
}
public List<ExampleModel> listExampleModel(Integer first, Integer count) {
Query tmp = getSession().createQuery("from ExampleModel");
if (first != null)
tmp.setFirstResult(first);
if (count != null)
tmp.setMaxResults(count);
return (List<ExampleModel>)tmp.list();
}
This is a really simple code to handle a limit or a list.
Criteria criteria=curdSession.createCriteria(DTOCLASS.class).addOrder(Order.desc("feild_name"));
criteria.setMaxResults(3);
List<DTOCLASS> users = (List<DTOCLASS>) criteria.list();
for (DTOCLASS user : users) {
System.out.println(user.getStart());
}
Below snippet is used to perform limit query using HQL.
Query query = session.createQuery("....");
query.setFirstResult(startPosition);
query.setMaxResults(maxRows);
You can get demo application at this link.
You can use below query
NativeQuery<Object[]> query = session.createNativeQuery("select * from employee limit ?");
query.setparameter(1,1);
#Query(nativeQuery = true,
value = "select from otp u where u.email =:email order by u.dateTime desc limit 1")
public List<otp> findOtp(#Param("email") String email);
I want to get the latest record from a table. My sql is as follow.
Select * from (select * from TABLE_1 WHERE paid=1 order by PAYMENTDATE
DESC) WHERE ROWNUM = 1
I tried to do it with HQL with the mapping pojo classes. It gave errors. My HQL is as follow.
SELECT pay FROM (SELECT payment FROM com.Table1 as payment WHERE
payment.paid=1 ORDER BY payment.paymentDate DESC) as pay where
pay.ROWNUM = 1
The error is,
net.sf.hibernate.QueryException: in expected: SELECT [SELECT pay FROM
(SELECT payment FROM com.TABLE1 as payment WHERE payment.paid=1 ORDER
BY payment.paymentDate DESC) as pay.ROWNUM = 1 ]
Normal queries without subqueries are working.
Eg:
SELECT payment FROM com.Table1 as payment WHERE payment.paid=1
Please help to solve this.
I am new to querydsl and already in love with it, but I can't get how to use an alias in this query.
QProduct product = QProduct.product;
JPQLQuery jPQLQuery =
from(product)
.where(product.name.locate(searchTerm).as("score").gt(0).or(product.code.locate(searchTerm).as("score").gt(0))).groupBy(product.baseProd);
List<Product> matchedNames = jPQLQuery.orderBy(new NumberPath<Integer>(Integer.class, "score").asc()).offset((pageNumber-1)*10).limit(10).list(product);
my first thought was something like this which throws an error with the generated query as:
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token:
as near line 3, column 31 [select product from
mesoft.meshopframework.model.Product product where
locate(?1,product.name) as score > ?2 or locate(?1,product.code) as
score > ?2 group by product.baseProd order by score asc]
could someone show me the coorect way to do this?? I hope it's not necessary for DB to calculate product.name.locate(searchTerm) or the other one again for sorting,
thanks
JPQL has a more restricted syntax compared to SQL, but I don't think your example would work in SQL either.
You can't use aliases in the where part and for order you will need pick one of the locate expressions or order by both of them.
I'm trying to translate a MySQL query to JPA.
I'm using MySQL5 and EclipseLink 2.4.2.
Here's the MySQL query :
SELECT s.id, s.startDate, CAST(GROUP_CONCAT(DISTINCT s.endDate ORDER BY s.date DESC) AS DATE) endDate
FROM table_s s
WHERE ...
GROUP BY s.id, s.startDate
id and date are primary key. They are represented by an embeddable id in JPA and fields are also readable in the entity (insertable/updatable = false).
Here's the JPA query :
SELECT s.id, s.startDate, SQL('CAST(GROUP_CONCAT(DISTINCT ? ORDER BY ? DESC) AS DATE)', s.endDate, s.date) AS endDate
FROM EntityS s
WHERE ...
GROUP BY s.id, s.startDate
The current issue is that the generated sql query does not include s.startDate for a reason I don't know.
If I simply change the code to SELECT s.id, s.startDate, s.endDate, it's working... but I really need to get the last endDate.
I tried MAX(s.endDate) but actually it does not give the last value (even if it currently works, it's not correct and can send a wrong result)
If someone got an idea or a solution, I would be pleased.
Ok, I made it otherwise :
SELECT s.id, s.startDate, s.endDate
FROM EntityS s
WHERE ...
AND s.date = (
SELECT MAX(s.date)
FROM EntityS s2
WHERE s2.id = s.id
AND s2.startDate = s.startDate
AND ...
)
GROUP BY s.id, s.startDate