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.List; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import com.nec.core.exception.ObjectNotFoundException; import com.nec.core.exception.TooManyObjectsException; import com.nec.crud.hibernate.HibernateSessionManager; import com.nec.harvest.constant.Constants; import com.nec.harvest.exception.ServiceException; import com.nec.harvest.model.Tighten; import com.nec.harvest.repository.TightenRepository; import com.nec.harvest.service.TightenService; /** * {@link TightenService} * * @author sondn * */ public class TightenServiceImpl implements TightenService { private TightenRepository repository; public TightenServiceImpl(TightenRepository tightenRepository) { this.repository = tightenRepository; } @Override public Tighten findByClassifyAndMonth(String shimeKbn) throws ServiceException { if (StringUtils.isEmpty(shimeKbn)) { throw new IllegalArgumentException("Tighten classification (ShimeKbn) must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; Tighten tighten = null; try { tx = session.beginTransaction(); Criterion criterion = Restrictions.conjunction().add(Restrictions.eq("shimeKbn", shimeKbn)) .add(Restrictions.eq("delKbn", Constants.STATUS_ACTIVE)); Criteria criteria = repository.getCriteria(session, Tighten.class); criteria.add(criterion); List<Tighten> tightens = repository.findByCriteria(criteria); // Release transaction tx.commit(); if (CollectionUtils.isEmpty(tightens)) { throw new ObjectNotFoundException( "Could not find the tighten for tighten classification (ShimeKbn) " + shimeKbn); } if (tightens.size() > 1) { throw new TooManyObjectsException( "Too many objects are matched with tighten classification (ShimeKbn) " + shimeKbn); } tighten = tightens.get(0); } catch (HibernateException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while finding a tighten that matches with " + "tighten classification " + shimeKbn, ex); } finally { HibernateSessionManager.closeSession(session); } return tighten; } }