📄 bookdaoimpl.java
字号:
package org.whatisjava.dang.dao.hibernate;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.whatisjava.dang.dao.BookDao;
import org.whatisjava.dang.util.DaoException;
public class BookDaoImpl implements BookDao {
private static Logger logger = Logger.getLogger(BookDaoImpl.class);
public List<?> findById(Integer id) throws DaoException {
Session session = null;
try {
session = HbSessionFactory.getSession();
Query query = session.createQuery("from Book b where b.id=?");
query.setParameter(0, id);
List<?> list = query.list();
return list;
} catch (HibernateException e) {
logger.error("", e);
throw new DaoException("", e);
} finally {
HbSessionFactory.closeSession();
}
}
public List<?> findByCategoryId(Integer categoryId, int rowsPerPage,
int page) throws DaoException {
Session session = null;
try {
session = HbSessionFactory.getSession();
Query query = session
.createQuery("from Book b where b.categoryId=?");
query.setParameter(0, categoryId);
query.setMaxResults(rowsPerPage);
query.setFirstResult(rowsPerPage * (page - 1));
List<?> list = query.list();
return list;
} catch (HibernateException e) {
logger.error("", e);
throw new DaoException("", e);
} finally {
HbSessionFactory.closeSession();
}
}
public int getTotalPagesByCategoryId(Integer categoryId, int rowsPerPage)
throws DaoException {
Session session = null;
try {
session = HbSessionFactory.getSession();
Query query = session
.createQuery("select count(*) from Book b where b.categoryId=?");
query.setParameter(0, categoryId);
List<?> list = query.list();
int totalRows =((Long) list.get(0)).intValue();
if (totalRows % rowsPerPage == 0) {
return totalRows / rowsPerPage;
} else {
return totalRows / rowsPerPage + 1;
}
} catch (HibernateException e) {
logger.error("", e);
throw new DaoException("", e);
} finally {
HbSessionFactory.closeSession();
}
}
public List<?> findByCategoryId(Integer categoryId) throws DaoException {
Session session = null;
try {
session = HbSessionFactory.getSession();
Query query = session
.createQuery("from Book b where b.categoryId=?");
query.setParameter(0, categoryId);
List<?> list = query.list();
return list;
} catch (HibernateException e) {
logger.error("", e);
throw new DaoException("", e);
} finally {
HbSessionFactory.closeSession();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -