Java tutorial
/* * Copyright(C) 2014 * NEC Corporation All rights reserved. * * No permission to use, copy, modify and distribute this software * and its documentation for any purpose is granted. * This software is provided under applicable license agreement only. */ package com.nec.harvest.service.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.transform.Transformers; import com.nec.crud.hibernate.HibernateSessionManager; import com.nec.harvest.constant.SqlConstants; import com.nec.harvest.exception.ServiceException; import com.nec.harvest.model.SmallCategory; import com.nec.harvest.repository.SmallCategoryRepository; import com.nec.harvest.service.SmallCategoryService; /** * {@link SmallCategoryService} * * @author huonghv * */ public class SmallCategoryServiceImpl implements SmallCategoryService { private static final String SMALL_CATEGORY_CLASSIFY = "2"; private SmallCategoryRepository repository; public SmallCategoryServiceImpl(SmallCategoryRepository smallCategoryRepository) { this.repository = smallCategoryRepository; } /** {@inheritDoc} */ @Override public List<SmallCategory> findAll() throws ServiceException { return findByClassify(SMALL_CATEGORY_CLASSIFY); } /** {@inheritDoc} */ @Override public List<SmallCategory> findByClassify(String classifyCategory) throws ServiceException { if (StringUtils.isEmpty(classifyCategory)) { throw new IllegalArgumentException("The category classify must not be empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; List<SmallCategory> smallCategories = new ArrayList<SmallCategory>(); try { tx = session.beginTransaction(); Query query = repository.getNamedQuery(session, SqlConstants.SQL_FIND_SMALL_CATEGORY); query.setResultTransformer(Transformers.aliasToBean(SmallCategory.class)); smallCategories = repository.findByQuery(query); // Release transaction tx.commit(); } catch (HibernateException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException( "Hibernate runtime exception occur when get small category with its classify " + classifyCategory, ex); } finally { HibernateSessionManager.closeSession(session); } return smallCategories; } }