I have a class that uses Hibernate HQL queries. I would like to change these into Hibernate Criteria queries.
However, Hibernate Criteria is a lot harder for me to understand than HQL, even with tutorials. Could someone show me how one of the queries would look like using Hibernate Criteria/Filters?
Configuration configuration = new Configuration();
configuration.configure().setProperty("hibernate.show_sql", "false");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(serviceRegistry);
Session session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from TABLENAME WHERE IDObject1= :idObjectA" +
"AND IDObject2= :idObjectB AND IDSettingOption = :idSettingOption");
query.setParameter("idObjectA", idObjectB);
query.setParameter("idObjectB", idObjectB);
query.setParameter("idSettingOption", idSettingOption);
List results = query.list();
Thanks in advance!
Criteria criteria = session.createCriteria( TABLENAME.class );
criteria.add( Restrictions.eq( "IDObject1" , idObjectB) );
criteria.add( Restrictions.eq( "IDObject2" , idObjectB) );
criteria.add( Restrictions.eq( "IDSettingOption" ,idSettingOption) );
List results = criteria.list();
Here you can read about Criteria API, it has a lot of examples:
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html
List results = session.createCriteria(Entity.class)
.add(Restrictions.eq("IDObject1", idObjectA))
.add(Restrictions.eq("IDObject2", idObjectB))
.add(Restrictions.eq("idSettingOption", idSettingOption))
.list();
Related
i have a table which contains following fields
|id|feedback_status|financial_year|attendence|behaviour|total_feedback|user_id|total_behaviour|
Iam fetching feedback_status and total_feedback from that table and return as json data using hibernate with projections and projectionlist.
List<StudentFeedback> results = null;
Session session = getSession();
Criteria criteria = session.createCriteria(StudentFeedback.class);
ProjectionList projlist = Projections.projectionList();
projlist.add(Projections.property("totalFeedback").as("qty"));
projlist.add(Projections.groupProperty("feedbackStatus").as("feedName"));
criteria.setProjection(projlist);
criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
results = criteria.list();
}
return GsonUtils.toGson(results);
}
My feedback_status and total_feedback contains following values
|feedback_status| |total_feedback |
Excellent 23
Average 11
Poor 12
Good 13
Poor 12
So the problem is whenever returning the json,it prints the feedback_status value poor two times and i want only the values to be printed once and if it occurs more than once then sum the total_feedback corresponding to the feedback_statusand returns to single one.
I got the answer by using groupProperty in hibernate porjections
By the way Thanks Pradeep CG
List<StudentFeedback> results = null;
Session session = getSession();
Criteria criteria = session.createCriteria(StudentFeedback.class);
ProjectionList projlist = Projections.projectionList();
projlist.add(Projections.sum("totalFeedback").as("qty"));
projlist.add(Projections.groupProperty("feedbackStatus").as("feedName"));
criteria.setProjection(projlist);
criteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
results = criteria.list();
return GsonUtils.toGson(results);
I have an sql query. Can anyone convert to hibernate criteria?
SELECT TH_ID,TH_NAME FROM t_o2_th_master WHERE TH_ID IN(SELECT TH_ID FROM t_o2_user_gameplay WHERE USER_ID=10010 AND STATUS_TYPE_CODE_ID=1303)
This is my entity class for fields name:
SELECT treasureHuntId,treasureHuntName FROM TreasureHuntMasterEntity WHERE treasureHuntId IN(SELECT treasureHuntId FROM UserGamePlayEntity WHERE userId:userID AND statusTypeCodeId:statusTypeCodeID)
change
WHERE userId:userID
to
WHERE userId = :userID
We can directly run SQL queries using hibernate. Hibernate provides two different types of queries
HQL queries. We can do everything that is possible in SQL
Criteria queries . We have define criteria based on objects.
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
Criteria criteria =session.createCriteria( t_o2_th_master.class );
criteria.createCriteria( "t_o2_user_gameplay", "user" );
criteria.add( Restrictions.eq( "user.userId", 10010 ) );
criteria.add( Restrictions.eq( "user.statusTypeId", 1303 ) );
t_o2_th_master masterList = criteria.list();
t_o2_th_master master=null;
if(masterList.size()>0){
master=masterList.get(0);
}
Is it possible to execute an update while using Criteria in Hibernate? For example:
Session session = getSession();
Criteria crit = session.createCriteria(User.class);
crit.add(Restrictions.eq("token", sessionToken));
User user= new User();
Transaction tx = session.getTransaction();
try
{
tx.begin();
session.updateWithCriteria(user, crit); //my imaginary function
tx.commit();
}
catch (Exception e)
{
e.printStackTrace();
tx.rollback();
}
session.close();
There is a very powerful feature called:
15.4. DML-style operations
small cite from doc:
... However, Hibernate provides methods for bulk SQL-style DML statement execution that is performed through the Hibernate Query Language...
So, while this is not about criteria - we still can use our domain model for querying, because it is about HQL. This is a snippet showing the power:
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update Customer c set c.name = :newName where c.name = :oldName";
// or String hqlUpdate = "update Customer set name = :newName where name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();
SUMMARY: Having that in place:
we can use query to filter results
we can apply bulk update on it
we won't need to load these rows in memory, into the session...
Now we can do something like this for bulk update and delete. New api's released for criteriaUpdate and CriteriaDelete
CriteriaBuilder cb = this.em.getCriteriaBuilder();
// create update
CriteriaUpdate<Order> update = cb.createCriteriaUpdate(Order.class);
// set the root class
Root e = update.from(Order.class);
// set update and where clause
update.set("amount", newAmount);
update.where(cb.greaterThanOrEqualTo(e.get("amount"), oldAmount));
// perform update
this.em.createQuery(update).executeUpdate();
First you should get the object then modify and update:
Query q = session.createQuery("from StockTransaction where tranId = :tranId ");
q.setParameter("tranId", 11);
StockTransaction stockTran = (StockTransaction)q.list().get(0);
stockTran.setVolume(4000000L);
session.update(stockTran);
If you want to use partial/dynamic update feature then put
#org.hibernate.annotations.Entity(
dynamicUpdate = true
)
annotation on top of the dao class.
Example from: http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/
Note: The Question is "with criteria" but the accepted answer is NOT "with criteria" but SQL.
I am trying to join multiple table to join using criteria but getting error in doing so can someone please help me in it
My code is
final Session session = getSession();
final Criteria criteria = session.createCriteria(ReferralPaymentInfo.class).createCriteria("SIGNUP_REFERRAL");
System.out.println("before");
List list = criteria.list();
System.out.println("after");
I also tried this code
final Session session = getSession();
final Criteria criteria =session.createCriteria(ReferralPaymentInfo.class);
criteria.setFetchMode("SIGNUP_REFERRAL", FetchMode.JOIN);
List list = criteria.list();
This gives result only from table ReferralPaymentInfo and not considering table SIGNUP_REFERRAL
Can some one please help me out
T
try this
DetachedCriteria ownerCriteria = DetachedCriteria.forClass(Owner.class);
ownerCriteria.setProjection(Property.forName("id"));
ownerCriteria.add(Restrictions.eq("ownername", "name"));
Criteria criteria = getSession().createCriteria(Pet.class);
criteria.add(Property.forName("ownerId").in(ownerCriteria));
I want to know how to make groupby in hibernate.
my code is below but it is not working please tell me how do this :
Session session = getSession();
Criteria c = session.createCriteria(CardLog.class);
c.add(Restrictions.ge(CARD_PUNCHING_TIME, todaysDate));
c.setProjection(Projections.groupProperty(USER_ID));
c.addOrder(Order.desc(USER_ID));
cardLogList = c.list();
System.out.println("----------------" + cardLogList);
i think you have to use like this
Session session = getSession();
Criteria c = session.createCriteria(CardLog.class);
c.add(Restrictions.ge("bean property todaydate", todaysDate));
c.setProjection(Projections.groupProperty("bean property userId"));
c.addOrder(Order.desc("bean property userId"));
cardLogList = c.list();
System.out.println("----------------" + cardLogList);