ansh
ansh

Reputation: 623

Case Statement in hibernate criteria

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

Upvotes: 0

Views: 6139

Answers (1)

spi
spi

Reputation: 1735

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:

Upvotes: 2

Related Questions