Syntax to get List of domain Object
list can be used on the Criteria object as shown below.
criteria.list()
How to get a List of a Domain class using Hibernate's Criteria Query.
If we have a domain class Category as shown below.Catgeory.class
package com.ekiras.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="category")
public class Category {
public Category(){}
public Category(Long id){
this.id = id;
}
public Category(Long id, String name){
this.id = id;
this.name = name;
}
@Id
@Column(nullable=false, name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(nullable=false, name="name")
private String name;
// Getters and Setters
}
- Simplest way to get a list of a Domain class (Category) in our example is
sessionFactory.getCurrentSession().createCriteria(Category.class).list();
- You can use pagination in the following way with list()
@SuppressWarnings("unchecked")
public List<Category>; list(Integer offset){
return sessionFactory.getCurrentSession()
.createCriteria(Category.class)
.setFirstResult(offset!=null?offset:0)
.setMaxResults(10)
.list();
} - Use this method as a generic method to get a list of all the records of a domain in the database.
@SuppressWarnings("rawtypes")
public List list(Class clazz){
return (List)getSession().createCriteria(clazz).list();
} - You can Order your list according to any property like
public List<Category> list(Integer offset){
return getSession()
.createCriteria(Category.class)
.addOrder(Order.desc("id"))
.list();
}
Comments
Post a Comment