Creating dynamic query using jpa criteria - java

I created dynamic query using jpa criteria but an extra pair of parentheses gets added to columns to be selected when I do userGroupSubquery.select(userGroupsRoot);
generated query
select (securitygr3_.group_name, securitygr3_.user_name) from gm.security_groupings securitygr3_ where 1=1 and securitygr3_.user_name='xxx' and (securitygr3_.group_name in ('XYZ'))
expected query:
select securitygr3_.group_name, securitygr3_.user_name from gm.security_groupings securitygr3_ where 1=1 and securitygr3_.user_name='xxx' and (securitygr3_.group_name in ('XYZ'))
Subquery<SecurityGroupings> userGroupSubquery = secUsersQuery.subquery(SecurityGroupings.class);
Root<SecurityGroupings> userGroupsRoot = userGroupSubquery.from(SecurityGroupings.class);
Path<SecurityGroupingsId> secGroupId = userGroupsRoot.get("id");
Path<SecurityUsers> secUsers = secGroupId.get("securityUsers_1");
Path<SecurityUsers> securityUsers = secGroupId.get("securityUsers");
Path<String> su_name = secUsers.get("name");
Path<String> name = securityUsers.get("name");
userGroupSubquery.select(userGroupsRoot);
userGroupSubquery.getCompoundSelectionItems();
//userGroupSubquery.where(criteriaBuilder.equal(pet.get(SecurityGroupingsId_.id), root.<String>get("name")));
Predicate restrictions3 = criteriaBuilder.conjunction();
restrictions3 = criteriaBuilder.and(restrictions3, criteriaBuilder.and(criteriaBuilder.equal(su_name, dto.getUserId().trim().toUpperCase())));
restrictions3 = criteriaBuilder.and(restrictions3, criteriaBuilder.and(name.in(userGroups)));
userGroupSubquery.where(restrictions3);
restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(userGroupSubquery));
}
secUsersQuery.where(restrictions);
Its just that I get an extra pair of parentheses at select (securitygr3_.group_name, securitygr3_.user_name) from
which gives me ora-00907 missing right parenthesis error. I am sure it is coming from userGroupSubquery.select(userGroupsRoot) but I am not sure why. Please help

I got the solution for the above. When the entity has a composite key, then in JPA criteria instead of doing
userGroupSubquery.select(userGroupsRoot);
we should do
userGroupSubquery.select(userGroupsRoot.get("id"));
where id is the composite id.

Related

Hibernate: Query to select values from multiple tables using CriteriaQuery

Let's say, I have a query like
Select a.valA, b.valB
from tableA a join tableB b on a.joinCol = b.joinCol
where a.someCol = 1.
I want to execute it using Hibernate (and Spring Data) in one query to the database. I know, I can write just
Query query = em.createQuery(...);
List<Object[]> resultRows = (List<Object[]>)query.getResultList();
But my question would be - is it possible to do it in a typesafe way, using CriteriaQuery for example? The difficulty is, that, as you see, I need to select values from different tables. Is there some way to do this?
Simple example where an Employee has many to many relation to several jobs that he may have :
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Tuple> criteria = builder.createTupleQuery();
Root<TableA> root = criteria.from(TableA.class);
Path<Long> qId = root.get("id");
Path<String> qTitle = root.get("title");
Join<TableA, TableB> tableTwo = root.join("joinColmn", JoinType.INNER);
criteria.multiselect(qId, qTitle, tableTwo);
List<Tuple> tuples = session.createQuery(criteria).getResultList();
for (Tuple tuple : tuples)
{
Long id = tuple.get(qId);
String title = tuple.get(qTitle);
TableB tableB= tuple.get(tableTwo);
}
but saw that there is an alternate answer here :
JPA Criteria API - How to add JOIN clause (as general sentence as possible)

JPA: Using criteriabuilder to find entities: Attribute name different from annotation?

I have a mysql database with employee information, each employee has a technical id as primary key. In MySQL to selcet row(s) matching criteria, i can just use to get the following statement (works)
SELECT * FROM database_test.employee WHERE fist_name='First1';
In Java i can also use this as a native statement to get what i want (works):
List<EmployeeEntity2> objects = m_em.createNativeQuery(
"SELECT * database_test.employee WHERE first_name='First1'",
EmployeeEntity2.class).getResultList();
However, i wanted to use the Criteriabuilder to get the same result and later generalize it for multiple columnName=columnEntry selections.
public List<EmployeeEntity2> testNoParameter() {
//Based on https://www.objectdb.com/java/jpa/query/criteria
CriteriaBuilder cb = m_em.getCriteriaBuilder();
CriteriaQuery<EmployeeEntity2> q = cb.createQuery(EmployeeEntity2.class);
Root<EmployeeEntity2> c = q.from(EmployeeEntity2.class);
ParameterExpression<String> p = cb.parameter(String.class);
//Works
//q.select(c).where(cb.equal(c.get("firstName"), p));
//Won't work
q.select(c).where(cb.equal(c.get("first_name"), p));
TypedQuery<EmployeeEntity2> query = m_em.createQuery(q);
query.setParameter(p, "First1");
List<EmployeeEntity2> results = query.getResultList();
return results;
}
Using "fist_name" - the column name annotation from the Entity - will yield the following java.lang.IllegalArgumentException with:
Unable to locate Attribute with the the given name [first_name] on this ManagedType [xx.xxx.database.EmployeeEntity2]
EmployeeEntity2 has "fist_name" annotation:
#Column(name = "first_name", nullable = false)
#Override
public String getFirstName() {
return super.getFirstName();
}
So "first_name" should exist, however (with some debugging) i found out that the attribute expected is for some reason "firstName" instead - which i have not defined/annotated - so where does it come from - and how can i use the column names actually defined in the database (column = "first_name")?
You should use property name of entity (not column name) to use it in criteria builder so instead of
q.select(c).where(cb.equal(c.get("first_name"), p));
use
q.select(c).where(cb.equal(c.get("firstName"), p));
CriteriaBuilder is RDBMS schema agnostic, so you use your model (entities), not schema (table names etc).
In JPA you dont normally use SQL but JPQL. Equivalent of your SQL in JPQL would be something like
"SELECT e FROM EmployeEntity2 e WHERE e.firstName='First1'"
Both CriteriaQuery tree and JPQL string are transformed down to the same query tree later on (can't remember the name), so they both must comply to the very same rules.

Hibernate Restrictions subquery with id of main query

I got 2 Tables with data
Main
---
id // 1
Second
---
id //1; 2
property //"a"; "b"
creationDate(DD/MM/YYYY) //01/01/2000; 02/02/2002
mainId // 1; 1
The connection is 1-*
So, what I want to do is to query my "Main" table by the property in "Second", but I want to search only the newest property.
So searching "a" must not give any result, as "b" is a newer data.
I wrota it via SQL and it looks like this:
select distinct m.id from Main m join Second s on m.id = s.mainId where s.property = 'b' and s.creationDate = (SELECT MAX(s2.creationDate) from Second s2 where s2.mainId = m.id);
I figured out some java code, but I have no idea how to use this s2.mainId = m.id part via Restrictions:
DetachedCriteria d = DetachedCriteria.forClass(Second.class, "s1");
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max("s1.creationDate"));
d.setProjection(proj).add(Restrictions.eq("WHAT COMES HERE");
Or maybe should I use defferent approach?
Unformtunately I need to use Hibernate Criterion Interface as whole seach mechanismus is written via Criterion.
DetachedCriteria innerCrit = DetachedCriteria.forClass(Second.class);
innerCrit.setProjection(Projections.max("creationDate");
innerCrit.add(Restrictions.eqProperty("id", "main.id"));
DetachedCriteriaouterCrit outerCrit = DetachedCriteria.forClass(Main.class, "main");
outerCrit.createAlias("second", "second");
outerCrit.add(Subqueries.eq(second.creationDate, innerCrit));
outerCrit.add(Restrictions.eq("second.property", "b"));
This outerCrit will get you the Main object.

Hibernate syntax error : Expected DOT

I am getting the following error on the execution of the below hibernate transaction : expecting DOT, found '=' near line 1, column 32 [update t_credential set status = :status , assigned_engine = :engine where id = :id] .
Also, t_credential is a table and not an object. Does hibernate allow to use this way or does it compulsorily have to be an object?
for(Credential credential: accountList){
Query query = ssn.createQuery("update t_credential set status =:status , assigned_engine = :engine where id = :id");
query.setParameter("status", status);
query.setParameter("engine", assignedTo);
query.setParameter("id", String.valueOf(credential.getId()));
int result = query.executeUpate();
}
Look at the HQL example here: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html#batch-direct. It seems that you need to refer to an object: "update t_credential c", and then update it's fields, like this: "set c.status = :status" and so on.
If you want to use Hibernate with SQL Query (and not HQL query), you may have to use a different function.
ssn.createSQLQuery(" ... ");
I never used this function, so I hope it's a good answer for you.
Max

Simple CriteriaQuery in JPA Criteria API that is too much for a noob

I am trying to write following SQL query using JPA Criteria API
SELECT * FROM roles WHERE roles.name IN (SELECT users.role FROM users where name="somename");
and it is a bit to much for me (I have just started learing Criteria API). I got something like this:
CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();
CriteriaQuery<RoleEntity> criteriaQuery = criteriaBuilder.createQuery(RoleEntity.class);
Root<RoleEntity> root = criteriaQuery.from(RoleEntity.class);
Subquery<UserEntity> subquery = criteriaQuery.subquery(UserEntity.class);
Root<UserEntity> subqueryRoot = subquery.from(UserEntity.class);
subquery.where(criteriaBuilder.equal(subqueryRoot.get(UserEntity_.username), username));
subquery.select(subqueryRoot);
And I have no idea how to put it all together.
Best regards,
Bartek
Fellow JPA learner here. Here's my attempt at setting it up:
// Get the criteria builder from the entity manager
CriteriaBuilder cb = manager.getCriteriaBuilder();
// Create a new criteria instance for the main query, the generic type indicates overall query results
CriteriaQuery<RoleEntity> c = cb.createQuery(RoleEntity.class);
// Root is the first from entity in the main query
Root<RoleEntity> role = criteriaQuery.from(RoleEntity.class);
// Now setup the subquery (type here is RETURN type of subquery, should match the users.role)
Subquery<RoleEntity> sq = cb.subquery(RoleEntity.class);
// Subquery selects from users
Root<UserEntity> userSQ = sq.from(UserEntity.class);
// Subquery selects users.role path, NOT the root, which is users
sq.select(userSQ.get(UserEntity_.role))
.where(cb.equal(userSQ.get(UserEntity_.username), username)); // test for name="somename"
// Now set the select list on the criteria, and add the in condition for the non-correlated subquery
c.select(role)
.where(cb.in(role).value(sq)); // can compare entities directly, this compares primary key identities automatically
Hopefully that helps!

Categories

Resources