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));
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 entity PrintingFare
and a foreign key there - Printer,
so how do I use Criteria API that way so I get a set of Printers, which have Printing fares?
Basically I have a class PrintingFare with this field
#ManyToOne
#JoinColumn(name = "printer_id", foreignKey = #ForeignKey(name = "fk_fares_ref_printer_id"))
private Printer printer;
How do I get a set of Printers using Criteria API?
I haven't tested this, but you can try:
Criteria criteria = getSession().createCriteria(PrintingFare.class);
criteria.setProjection(Projections.distinct(Projections.property("printer"));
List<Printer> list = criteria.list();
Let me know if it works. It will probably have to be tweaked.
You should add restrictions to the query
Criteria criteria = getSession().createCriteria(PrintingFare.class);
criteria.add(Restrictions.eq("printer.id", printerId));
List<PrintingFare> list = criteria.list();
Criteria criteria = getSession().createCriteria(Printer.class);
criteria.createAlias("printerFairs", "pf").add(Restrictions.in("pf.id", printerFairIds));
List<Printer> list = criteria.list();
If PrinterFares is mapped from the Printer.class side ...
Criteria criteria = getSession().createCriteria(Printer.class);
criteria.createAlias("printerFares", "pf");
criteria.add(Restrictions.isNotEmpty("pf"));
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List<Printer> printers = criteria.list();
If you are unable to change the mapping of Printer.class ...
Criteria criteria = getSession().createCriteria(Printer.class);
// create a subquery
DetachedCriteria dc = DetachedCriteria.forClass(PrinterFare.class);
dc.setProjection(Projections.property("printer.id"));
// restrict by subquery
criteria.add(Subqueries.in("id", dc);
crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
List<Printer> printers = criteria.list();
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 have the following criteria that I am using,..
List<boop> books =null;
Criteria criteria = session.createCriteria(boop.class);
ProjectionList proList = Projections.projectionList();
proList.add(Projections.property("AAA"));
proList.add(Projections.property("BBB"));
RETURN criteria.list();
please advise how can I convert it in HQL..
Have a look at the Projections javadoc. Each Projections property corresponds to a database field.
select b.AAA, b.BBB
from boop b
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);