Skip to content

Instantly share code, notes, and snippets.

@yusufcakmak
Created August 4, 2015 21:08
Show Gist options
  • Select an option

  • Save yusufcakmak/e26775d574ad60315eb1 to your computer and use it in GitHub Desktop.

Select an option

Save yusufcakmak/e26775d574ad60315eb1 to your computer and use it in GitHub Desktop.
package co.mobiwise.hibernate.app;
import co.mobiwise.hibernate.model.Book;
import co.mobiwise.hibernate.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import java.util.List;
/**
* Created by yusufcakmak on 8/4/15.
*/
public class HibernateCriteriaExample {
@SuppressWarnings("unchecked")
public static void main(String args[]) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = session.beginTransaction();
//get all books
Criteria criteria = session.createCriteria(Book.class);
List<Book> bookList = criteria.list();
for(Book book : bookList){
System.out.println("id :"+book.getId()+", Book Name :"+book.getBookName());
}
// Get with ID, creating new Criteria to remove all the settings
criteria = session.createCriteria(Book.class)
.add(Restrictions.eq("id", new Long(3)));
Book book = (Book) criteria.uniqueResult();
System.out.println("Book Name :" + book.getBookName() + ", Book Desc :"
+ book.getBookDesc());
//Pagination Example
bookList = session.createCriteria(Book.class)
.addOrder(Order.desc("id"))
.setFirstResult(0)
.setMaxResults(2)
.list();
for(Book bookPagination : bookList){
System.out.println("Paginated Books::" + bookPagination.getId() + "," + bookPagination.getBookName());
}
//Like example
bookList = session.createCriteria(Book.class)
.add(Restrictions.like("name", "%i%"))
.list();
for(Book bookLike : bookList){
System.out.println("Books having 'i' in name::"+bookLike.getBookName()+","+bookLike.getBookDesc());
}
//Projections example
long count = (Long) session.createCriteria(Book.class)
.setProjection(Projections.rowCount())
.add(Restrictions.like("name", "%i%"))
.uniqueResult();
System.out.println("Number of books with 'i' in name="+count);
// Rollback transaction to avoid messing test data
tx.commit();
// closing hibernate resources
sessionFactory.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment