hibernate groupby - java

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);

Related

hibernate Projections for spring boot application

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);

Delete all objects from database in hibernate Spring java

I want to delete all those rows from xyz table where id = 1 using hibernate spring.
I have tried following code but its not giving error but not deleting rows -
Session session = (Session) getEm().getDelegate();
String sql ="Delete from xyz where id=:id" ;
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("id", "1");
int flg = query.executeUpdate();
Can you please help me to delete all rows using hibernate query.
Try wrapping your code within a transaction like this:
Session session = (Session) getEm().getDelegate();
Transaction tx = session.beginTransaction();
String sql ="Delete from xyz where id=:id" ;
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("id", "1");
int flg = query.executeUpdate();
tx.commit();
Try
query.setParameter("id", Long.valueOf(1));
if your entity is of type Long (which ideally should be).
Reference: http://www.codejava.net/frameworks/hibernate/hibernate-basics-3-ways-to-delete-an-entity-from-the-datastore
Note: The link is just for your reference.
public void deleteById(Class clazz,Integer id) {
String hql = "delete " + clazz.getName() + " where id = :id";
Query q = session.createQuery(hql).setParameter("id", id);
q.executeUpdate();
}

Hibernate execute update with criteria

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.

Java Hibernate HQL to Hibernate Criteria

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();

How to join tables using hibernate criteria

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));

Categories