Case Statement in hibernate criteria - java

I am very new in hibernate I have an MySQL Query and I want to achive same output using Hibernate criteria
MySQL Query:
SELECT *,
(case when status = 'Active'
then 'Can Login'
else 'Not able to login' end) as LoginStatus
FROM UserLoginTable;
My Hibernate Code:
SessionFactory sessionFactory = HibernateUtility.getSessionFactory();
Session session_hiber = sessionFactory.openSession();
session_hiber.beginTransaction();
Criteria criteria;
criteria = session_hiber.createCriteria(UserLoginTable.class);
List<UserLoginTable> myUserList = (List<UserLoginTable>)
criteria.list();
How I can add the Case criteria in the above code.
Is there any way ?
Thanks

Although I did not test this snippet, you may try to use CriteriaBuilder something like this:
CriteriaBuilder cb = session_hiber.getCriteriaBuilder();
cb.selectCase()
.when(cb.equal(path.get("status"), "Active"), "Can Login")
.otherwise("Not able to login")
.alias("LoginStatus");
Some help/info can be found here:
CASE statement in HQL or Criteria
Using the 'case...when...then...else...end' construct in the 'having' clause in JPA criteria query
https://docs.oracle.com/javaee/6/api/javax/persistence/criteria/CriteriaBuilder.html

Related

Hibernate 5 select from table

I am using hibernate 5 (I am not familiar with hibernate, just started with it) and I want to perform a simple select query, after searching I found the following code to select an element by id:
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Ord> query = cb.createQuery(MyClass.class);
Root<Ord> root = query.from(MyClass.class);
query.select(root);
query.where(cb.equal(root.get(MyClass.NUM),ordId));
Query<Ord> sessionQuery = session.createQuery(query);
return sessionQuery.getSingleResult();
I find it a heavy way to just get just one element.
The question is: Is the above the recommended/correct way to fetch data using hibernate (5)?
Thanks in advance,
JPQL provides us with a quicker and simpler implementation while using the Criteria API is more dynamic and robust.
public List<Student> findAllStudentsWithJpql() {
return session.createQuery("SELECT a FROM Student a", Student.class).getResultList();
}
You are using Criteria API
The Criteria API provides a dynamic approach for building JPA queries.
public List<Student> findAllStudentsWithCriteriaQuery() {
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Student> cq = cb.createQuery(Student.class);
Root<Student> rootEntry = cq.from(Student.class);
CriteriaQuery<Student> all = cq.select(rootEntry);
TypedQuery<Student> allQuery = session.createQuery(all);
return allQuery.getResultList();
}
Above two methods are the common way in Hibernate.
Documentation - https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html
You can perform something like this...
#Autowired
private SessionFactory session;
Query<Your Class> query = session.getCurrentSession().createQuery("select * from <tableName>);

HIbernate criteria builder sum with if condition

SQL QUERY:
SELECT SUM(IF(table.type='type1', 1, 0)) as type1,SUM(IF(table.type='type2', 1, 0)) as type2 from table;
How to write same query in criteria builder like below:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> criteria = builder.createQuery( Object[].class );
Root<Table> root = criteria.from( Table.class );
criteria.multiselect(builder.sum())
I am unable to place if condition in criteria builder.
Note: there is bean class for Table.
Thanks in advance.
Apparently hibernate criteria does not support IF. I would consider just making 2 queries with criteria or using HQL or just native SQL.

How to use Delete query in Hibernate

I'm using Hibernate to delete the records from a table,but this giving an exception, could anyone know how to overcome this problem in the below query?
Session ses = HibernateUtil.getSessionFactory().openSession();
Transaction tx = ses.beginTransaction();
Query q = ses.createQuery("from RegisterPojo where email =:email");
q.setParameter("email", sl_no);
RegisterPojo pojo = (RegisterPojo) q.list().get(0);
ses.delete(pojo);
tx.commit();
ses.close();
Why not ?
Query q = ses.createQuery("delete from RegisterPojo where email =:email");
q.setParameter("email", sl_no);
q.executeUpdate();
Learn HQL
Before proceeding please learn more about hql. That reduces large amount of code.

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!

Hibernate Group by Criteria Object

I would like to implement the following SQL query with Hibernate Criteria:
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name <operator> value
GROUP BY column_name
I have tried to implement this with Hibernate Criteria but it didn't work out.
Can anyone give me an example how this can be done with Hibernate Criteria?
Thanks!
Please refer to this for the example .The main point is to use the groupProperty() , and the related aggregate functions provided by the Projections class.
For example :
SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name
Its equivalent criteria object is :
List result = session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).list();
GroupBy using in Hibernate
This is the resulting code
public Map getStateCounts(final Collection ids) {
HibernateSession hibernateSession = new HibernateSession();
Session session = hibernateSession.getSession();
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
Map stateMap = new HashMap();
for (Object[] obj : results) {
DownloadState downloadState = (DownloadState) obj[0];
stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
}
hibernateSession.closeSession();
return stateMap;
}
You can use the approach #Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:
session.createCriteria(SomeTable.class)
.add(Restrictions.ge("someColumn", xxxxx))
.setProjection(Projections.projectionList()
.add(Projections.groupProperty("someColumn"))
.add(Projections.max("someColumn"))
.add(Projections.min("someColumn"))
.add(Projections.count("someColumn"))
).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));
List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();
If you have to do group by using hibernate criteria use projections.groupPropery like the following,
#Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;

Categories

Resources