How can create HQL Query like Laravel? - java

My laravel eloquent is the following:
Module::select(['a', 'b'])
->whereRaw("OR a ='one' OR a = 'five' OR a ='ten'")
->distinct()
->orderBy('a', 'ASC')
->get();
How can I convert it into hibernate?

You can use the toSql() method to get the SQL query.
For example
DB::table('users')->toSql();
returns the query
select * from users
Then you have to translate the SQL to HQL, using some manual.

Spring Data allows you to create queries using the method name.
Example:
List<Module> findDistinctModuleByAOrderByAAsc(String a);

Related

How to add date in mysql database from Hibernate/Spring Jpa

I use spring boot, and I want to add 1 year to a specific column in mysql database
String queryRecherche = "UPDATE myTable t SET t.dateDebut = DATE_ADD(t.dateDebut, INTERVAL 1 YEAR) WHERE.id = 3 ";
Query query = em.createQuery(queryRecherche);;
query.executeUpdate();
But I get the folowing error :
org.hibernate.query.sqm.ParsingException: line 1:66 no viable alternative at input 'DATE_ADD(t.dateDebut,INTERVAL1'
Have you please any suggestions to do this.
You're using Hibernate 6 (I can tell by the error message), so the correct HQL syntax to use is:
UPDATE MyEntity t SET t.dateDebut = t.dateDebut + 1 year WHERE t.id = 3
You had three errors in your query:
You referred to the name of a table instead of the name of an entity class in the UPDATE clause.
You used the unportable MySQL DATE_ADD function instead of the portable HQL date/time arithmetic described here.
The syntax of your WHERE clause was garbled.
Perhaps you meant for this to be a native SQL query, in which case you called the wrong method of Session. But there's no need to use native SQL for the above query. As you can see, HQL is perfectly capable of expressing that query.
You can use SQL directly, via createNativeQuery, or register a new function as shown in this example to call it from HQL

Using dynamic where clause in Java JDBC

Using Java 11 and JDBC.
Having PostgreSQL table "employee":
I need to have an ability to select data, but I don't know in advance, what WHERE conditions would be used.
It could be:
SELECT * FROM employee WHERE job_name='PRESIDENT';
SELECT * FROM employee WHERE job_name='PRESIDENT' OR salary>6000;
SELECT * FROM employee WHERE salary<5000 AND manager_id=68319;
Writing all possible SQL in the code, would take a lot of time.
Probably, there is some library, that already has implementation for it.
Try sqlBuilder [http://sqlobject.org/SQLBuilder.html]. it has support to build dynamic where clauses based on condition. something like below
var query = SQL
.SELECT("*")
.FROM("employee")
.WHERE()
._If(job_name=="PRESIDENT", "job_name = {0}", job_name)
.ORDER_BY("job_name");

How to change order with TypedQuery in JPA

I wish to implement pagingation with FIQL support.
I am using apache cxf with JPA(Hibernate).
Here is sample example given for it http://cxf.apache.org/docs/jax-rs-search.html#JAX-RSSearch-JPA2.0
SearchConditionVisitor<Order, TypedQuery<Order>> visitor
= new JPATypedQueryVisitor<>(em, Order.class);
// connect FIQL cxf SearchCondition with our JPA visitor
searchCondition.accept(visitor);
// creeate JPA specific TypedQuery by our visitor
TypedQuery<Order> typedQuery = visitor.getQuery();
typedQuery.setFirstResult((page * perPage) - perPage);
typedQuery.setMaxResults(perPage);
// Run the query and return matching a complex FIQL criteria
return typedQuery.getResultList();
Every thing looks working including searching and pagination.
It looks have no order by clause being use from generate sql log and seems follow database insertion order.
Now I wish to change the default sorting order. For example I wish to sort by Order id field in descending order. How can I achieve that?
I can get it working with use of CriteriaQuery.
JPACriteriaQueryVisitor<Order, Order> jpa
= new JPACriteriaQueryVisitor<>(em, Order.class, Order.class);
searchCondition.accept(jpa);
CriteriaQuery<Order> cq = jpa.getCriteriaQuery();
CriteriaBuilder cb = em.getCriteriaBuilder();
Root<Order> root = (Root<Order>) cq.getRoots().iterator().next();
cq.orderBy(cb.desc(root.get("id")));
TypedQuery<Order> query = jpa.getTypedQuery();
query.setFirstResult((page * perPage) - perPage);
query.setMaxResults(perPage);
return query.getResultList();
You cannot change the order after creating the query.
If you use MySQL, then maybe you can use an integer parameter in ORDER BY :colnum DESC to specify the column number by which to sort (starting at 1 from the selected columns only), but you cannot change direction.
PostgreSQL does not allow you to do this. I do not know how it is on other databases, though. With MySQL, the parameters are replaced by the SQL Driver, so it always receives the full query with escaped sequences. With PG, the query is first parsed by the server, the execution plan is created (including if and how to order the results) and then the parameters are sent.

Criteria Query returnig all records

SQL :
String hql1 = "SELECT /* PARALLEL(MVR,16) PARALLEL(MVRS,16)*/ * FROM
ICM MINUS SELECT I1.* FROM ICM I1 , C1_ICM_STATIC I2 WHERE
I1.METRIC_DIRECTION=I2.METRIC_DIRECTION AND
I1.METRIC_NAME=I2.METRIC_NAME AND I1.METRIC_UNIT=I2.METRIC_UNIT AND
I1.TERMINATION_POINT_ID=I2.TERMINATION_POINT_ID AND
I1.TERMINATION_POINT_NAME=I2.TERMINATION_POINT_NAME AND
I1.TERMINATION_POINT_TYPE=I2.TERMINATION_POINT_TYPE";
Criteria Query
icms1 = (List<ICM>) session.createCriteria(ICM.class, hql1).list();
I have executed hql1 using SQL Developer then I got only one result, but when I have integrated SQL Query with Criteria it returning me all records in ICM table.
If SQL query returning only one result in SQL Developer, Why criteria API returning all records in ICM table?
Why criteria API returning all records in ICM table?
Technically you are not using criteria api for associations.
Try something like this.
Refer.
return criteria.createCriteria(A.class)
.createCriteria("b", "join_between_a_b")
.createCriteria("c", "join_between_b_c")
.createCriteria("d", "join_between_c_d")
.add(Restrictions.eq("some_field_of_D", someValue));
You should learn to read API documentation.
The second Session.createCriteria() argument is the alias that you want to assign to the root entity. It's not a HQL query. HQL queries are not executed using Session.createCriteria(). They're executed using Session.createQuery().
BTW, your query is not a HQL query at all. It's a SQL query. SQL and HQL are 2 different languages. To execute a SQL query, you need createSQLQuery().

pass a array in querybuilder in statement

I am using a query builder to create a query statement in hibernate. i need to pass a arrayList for in statement. How can this be done.
Dummy code :
List<String> xyz = new ArrayList<String>("sam","tam","vam");
StringBuilder queryBuilder = new StringBuilder("select abc from tem where xyz in :xyzList");
Query query = entityManager.createNativeQuery(queryBuilder.toString());
query.setParameter("xyzList", xyz);
query.getResultList();
this is not working. it throws exceptions. Can somebody point me how to do this.
Use setParameterList("xyzList", new String []{"a","b","c"});
So if you have the list with you, you can do list.toArray() in place of new String []{"a","b","c"}
You have seemed to be mistaken an entityManager.createNativeQuery with entityManager.createNamedQuery or entityManager.createQuery
The syntax of your query is JPQL, but you compile it as a native query syntax
What should work for you is to move from createNativeQuery simply to createQuery, or align it the other way around so write a proper native query if that is your goal.
Note just that if you're intent was to go for a native query you should stay away from the named parameters. In your case it would work since you're using hibernate as persistence provider, but otherwise, named parameters in native queries are not supported according to JPA specification

Categories

Resources