I have two entity: Issue and Issue_Tracker. I am using Hibernate 3.6.
SELECT `issues`.`issue_id`,
`issues`.`issue_raised_date`,
`issues`.`issue_description`,
`issue_tracker`.`tracker_status`
FROM `issues`
LEFT JOIN `issue_tracker` ON `issues`.`issue_id` = `issue_tracker`.`issue_id`
WHERE `issues`.`status`="Escalate To"
How to achieve this using Hibernate Criteria, and most Important, I have to use it for pagination.
and My Dao is as follows to show the list of Issues in jqgrid
public List showHelpDeskIssues(DetachedCriteria dc, int from,
int size) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try
{
Criteria criteria = dc.getExecutableCriteria(session);
criteria.setFirstResult(from);
criteria.setMaxResults(size);
criteria.add(Restrictions.eq("status","Escalate To"));
return criteria.list();
}
catch (HibernateException e)
{
e.printStackTrace();
throw e;
} }
For brief explanation please refer this question how to show two tables data in jqgrid using struts2 - jqgrid plugin and hibernate
any help would be great.
you can try the following
Criteria criteria = session.createCriteria(Issues.class);
criteria.setFirstResult(from);
criteria.setMaxResults(size);
criteria.setFetchMode('parent.child', FetchMode.JOIN);
criteria.add(Restrictions.eq("status", "Escalate To"));
List<Issues> list= criteria.list();
here parent is the property name in Issues.java and child is the property in IssueTracker.java.
Well,
follow one sample...
Criteria crit = session.createCriteria(Issues.class);
crit.createAlias("otherClass", "otherClass");
crit.add(Restrictions.eq("otherClass.status", "Escalate To"));
List result = crit.list();
I think so this can to help!!
Try this out because this worked for me
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Issues.class, "issues");
criteria.setFetchMode("issues.issuetracker", FetchMode.JOIN);
criteria.createAlias("issues.issuetracker", "issuetracker");
criteria.add(Restrictions.eq("status","Escalate To"));
List list = criteria.list();
return list;
Note: In Hibernate criteria, inner outer join and inner join are one and the same. Do not get confused.
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try{
Criteria criteria = session.createCriteria(Issues.class, "issues");
criteria.setFirstResult(from);
criteria.setMaxResults(size);
criteria.createAlias("issues.issuestracker", "issuestracker", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("issues.status", "Escalate To"));
return criteria.list();
}catch(HibernateException e){
e.printStackTrace();
throw e;
}
This should solve your issue. Let me know if you face any trouble.
Related
Well, I do not understand why me code does not work. Could Someone please take a look. It does not provide any error messages but the Customer will not be deleted. Other methods are working well (getCustomerbyId, getAllCustomers and so)
Thanks
public void deleteCustomerById(long id) {
EntityManager em = null;
try {
em = JpaUtil.getFactory().createEntityManager();
em.getTransaction().begin();
Query query = em.createQuery("Delete from Customer c where c.id = :id");
query.setParameter("id", id);
em.getTransaction().commit();
} finally {
JpaUtil.closeQuietly(em);
}
}
You need to execute queries to have SQL issues to the database; in this case you will want to use executeUpdate() and get the modified row count to verify something was deleted or not.
em.getTransaction().begin();
Query query = em.createQuery("Delete from Customer c where c.id = :id");
query.setParameter("id", id);
int rows = query.executeUpdate();
em.getTransaction().commit();
You are creating a query but not executing it.
You should add
query.executeUpdate();
before committing
Use jpa APis find(Customer.class) to find the customer object then use romove(object)
I want to write the below query using criteria .
I need to find the distinct rows and also use the current date in where clause .How can I achieve this in Criteria.
SELECT DISTINCT *
FROM EMAIL_PROGRAM
WHERE CURRENT_DATE >=PGM_START_DT
AND CURRENT_DATE <= PGM_END_DT
AND EMAIL_PGM_FLG ='Y'
AND EMAIL_PGM_DESC IS NOT NULL
and RGN_CD = 'US';
Below is my code in which I need to apply .
SessionFactory factory = null;
Session session = null;
try {
factory = getSessionFactory();
session = factory.openSession();
final Criteria criteria = session
.createCriteria(EmailDataBean.class);
returnList = criteria.list();
} catch (Exception e) {
logger.error(e.getMessage());
throw new DAOException(e);
} finally {
DBUtil.close(factory, session);
}
if (logger.isInfoEnabled()) {
logger.info(LOG_METHOD_EXIT);
}
return returnList;
}
you can use below on your criteria object.
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
You should do something like
//first add conditions in the where clause (you should use property names as defined in your Hbernate entities , not column names in your DB)
criteria.add(Restrictions.ge("PGM_START_DT", startDt));
criteria.add(Restrictions.le("PGM_END_DT", endDt));
criteria.add(Restrictions.eq("EMAIL_PGM_FLG", "Y"));
criteria.add(Restrictions.isNotNull("EMAIL_PGM_DESC"));
criteria.add(Restrictions.eq("RGN_CD", "US"));
Now, add every column (i.e. a Hibernate entity property/field) to a Projection list (this is needed to support distinct in the query)
ProjectionList pList = Projections.projectionList();
pList.add(Projections.property("PGM_START_DT"), "PGM_START_DT");
pList.add(Projections.property("PGM_END_DT"), "PGM_END_DT");
// add all the other properties (columns) and then have the Projections.distinct method act on the entire row (all the columns)
criteria.setProjection(Projections.distinct(pList));
By default, using Projections does return the result as a List<Object[]> rather than List<EmailDataBean>, which is usually not convenient. To remedy that, you should set a ResultTransformer
crit.setResultTransformer(Transformers.aliasToBean(EmailDataBean.class));
Alternatively, instead of using Projections, you can use
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
but this will not fetch distinct rows from the database but rather have Hibernate filter the results (removing the duplicates).
I have a very long object, so to make the system faster, I decided to show only the top 5 on "attendance" attribute (insted to show all the elements) when retrieve by the "get" service.
I have a attendances list, but there is a way to say only get the top 5 (on the list get) and when I got the results from the "detail" service, I will have all the itens.
#ManyToMany
private List<Attendance> attendance;
Write a custom repostitory, inject the entitymanager and use a query like that:
entityManager.createQuery("Select a from Enity e join e.attendence a")
.setMaxResults(5)
.getResultList();
Even you can do by Hibernate Criteria:
public List findByLimit(Class persistentClass, String orderproperty, int limit)
{
Session session = getSession(); // Get Session here
try
{
Criteria criteria = session.createCriteria(persistentClass);
criteria.addOrder(Order.desc(orderproperty));
criteria.setMaxResults(limit);
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return criteria.list();
}
catch (RuntimeException re)
{
//Catch exception
}
finally
{
//close the session
}
}
Now call the above function :
findByLimit(Example.class,id,5); // here id is your order property
I have a method like below
public List<String> getSimilarResourceNames(String resourceName){
String searchString = "%"+resourceName+"%";
Session session = getSession();
Criteria criteria = session.createCriteria(Resource.class);
criteria.add(Restrictions.like("name", searchString));
return criteria.list()
}
This will return me the entire resource from the DB, but what i need is just the name of the resource. How can I accomplish that ?
Use Projection, you can find examples in Hibernate documentation.
Criteria criteria = session.createCriteria(Resource.class);
criteria.setProjection(Property.forName("name"))
criteria.add(Restrictions.like("name", searchString));
By using Projection you will get other fields (Which you did not got by Projection) in your Pojo setted to default values. In HQL you can get specified column values as follow:
Query query = session.createQuery("select u.fullname from Users u");
List<Object[]> rows = query.list();
List<String> fullnames = new ArrayList<String>();
for (Object[] row: rows) {
fullnames.add(row[0]);
}
I hope this will help you.
I'm facing the following problem:
Criteria criteria = getSession().createCriteria(User.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("id"));
projectionList.add(Projections.countDistinct("friend_id"));
projectionList.add(Projections.property("registrationDate"));
projectionList.add(Projections.property("lastLoginDate"));
criteria.setProjection(projectionList);
this piece of code returns me a couple of entries with the data I require. However, I need the rowcount for it. Is there a clean way of doing this, rather than just doing a:
return criteria.list().size();
?
Criteria criteria = session.createCriteria(Track.class)
.setProjection(Projections.rowCount());
List result = criteria.list();
if (!result.isEmpty()) {
Integer rowCount = (Integer) result.get(0);
System.out.println("Total records: " + rowCount);
What if you add this to the end of the ProjectionList?
Projections.rowCount()
I use the following code to search something and then get the rowcount for it.
Criteria criteria = session.createCriteria(LogEntryOracle.class);
if (search != null && !search.isEmpty()) {
criteria.add(Restrictions.ilike("xml", search, MatchMode.ANYWHERE));
}
criteria.setProjection(Projections.rowCount());
return (Number) criteria.uniqueResult();
Seems that my problem was caused by the lack of analysis:
Criteria criteria = getSession().createCriteria(User.class);
criteria.setProjection(Projections.countDistinct("id"));
return (Long) criteria.uniqueResult();
since we're already grouping by the user ID then all I had to do is find the amount if unique user IDs matching the search criteria.