开发者

Hibernate Paging

I know through setMaxResults & setFristResults method of Criteria in Hibernate i can do paging.. but my question is how do i separate it from DAO, I mean where i implement the DAO only there i am able to specify the setMaxResults() & setFristResults() value, i want to make it as a separate layer,because if suppose there is around 500 DAO's various module then its difficult to change accordingly,

Here is the code : Domain :

public class Demo implements java.io.Serializable {
private int id;
private Date date;
private String weekday;
private Double cost;

public Demo() 
{

}

public Demo(Date date, String weekday, Double cost) 
{
    this.date = date;
    this.weekday = weekday;
    this.cost = cost;
}
/***Setter & getter***/
}

DAO :

public interface DemoDAO {

public void setPage(Page page);
public List<Demo> findAll();
}


public class DemoDAOImpl implements DemoDAO  {
private HibernateDAO hibernateDAO;
private Session session;
private Page page;

public DemoDAOImpl()
{
    hibernateDAO = new HibernateDAOImpl();
    session = hibernateDAO.getSession();
}

public void setPage(Page page) 
{
    this.page = page;
}

public List<Demo> findAll() 
{
    session.beginTransaction();
    Criteria criteria = session.createCriteria(Demo.class);
    criteria.setFirstResult(page.getPageNumber() * page.getPageSize());
    criteria.setMaxResults(page.getPageSize());

    List<Demo> demoList = criteria.list();
    session.getTransaction().commit();

    return dem开发者_StackOverflowoList;
}

Service :

public interface DemoService {

public List<Demo> showDetails(Page page);
}



public class DemoServiceImpl implements DemoService {
private DemoDAO demoDAO;

public DemoServiceImpl()
{
    demoDAO = new DemoDAOImpl();
}

public List<Demo> showDetails(Page page) 
{
    if(page != null)
        demoDAO.setPage(page);
    else
        page = new Page(0,50);

    return demoDAO.findAll();
}
}

now from the frontend i am calling this showDetails...

please correct me if i am using the correct thing...


You are thus making your DAO stateful, and that is not so good.

You can pass the Page as argument to each method instead. Thus a single instance of the DAO will be sufficient.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜