/**
 * ÀÌ ¼Ò½º´Â Spring ÇÁ·¹ÀÓ¿öÅ© ¿öÅ©ºÏ¿¡¼­ »ç¿ëÇÑ ¿¹Á¦ ¼Ò½ºÀÔ´Ï´Ù. 
 * ÀÌ ¼Ò½º´Â ¸ðµç °³¹ßÀÚµéÀÌ ÀÚÀ¯·Ó°Ô ¼öÁ¤ ¹× ¹èÆ÷ÇÒ ¼ö ÀÖ½À´Ï´Ù. 
 * ´Ü, ÀÌ ¼Ò½º¸¦ ±â¹ÝÀ¸·Î »õ·Î¿î ¾ÖÇÃ¸®ÄÉÀÌ¼ÇÀ» °³¹ßÇÒ °æ¿ì ÃâÃ³¸¦ ¸í½ÃÇØ ÁÖ½Ã¸é µË´Ï´Ù. 
 */
package net.javajigi.board.dao;

import java.sql.SQLException;
import java.util.List;

import net.javajigi.board.model.Board;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class BoardDAOHibernate extends HibernateDaoSupport implements BoardDAO {

	public Board insert(Board board) throws DataAccessException {
		getHibernateTemplate().save(board);

		return board;
	}

	public Board update(Board board) throws DataAccessException {
		getHibernateTemplate().update(board);

		return board;
	}

	public int delete(int boardNo) throws DataAccessException {
		getHibernateTemplate().delete(findBoard(boardNo));

		return 1;
	}

	public Board findBoard(int boardNo) throws DataAccessException {
		Board board = (Board) getHibernateTemplate().get(Board.class,
				new Integer(boardNo));
		if (board == null) {
			throw new ObjectRetrievalFailureException(Board.class, new Integer(
					boardNo));
		}

		return board;
	}

	public List findBoardList(final int currentPage, final int countPerPage)
			throws DataAccessException {
		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session
						.createQuery("from Board board order by board.createDate");
				int start = (currentPage - 1) * countPerPage;
				query.setFirstResult(start);
				query.setMaxResults(countPerPage);

				return query.list();
			}
		});
	}

	public int updateHitCount(int boardNo) throws DataAccessException {
		Board board = (Board) getHibernateTemplate().get(Board.class,
				new Integer(boardNo));
		if (board != null) {
			board.setHitCount(board.getHitCount() + 1);
		}

		getHibernateTemplate().update(board);

		return 1;
	}

	public int getTotalNo() throws DataAccessException {
		List resultList = getHibernateTemplate().find(
				"SELECT count(board) FROM Board board");
		Integer totalNo = (Integer) resultList.get(0);

		return totalNo.intValue();
	}
}
