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 org.hibernate.exception.JDBCConnectionException; 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.ConnectionException; import com.nec.harvest.exception.ServiceException; import com.nec.harvest.model.User; import com.nec.harvest.repository.UserRepository; import com.nec.harvest.service.UserService; /** * {@link UserService} * * @author sondn * */ public class UserServiceImpl implements UserService { private UserRepository repository; public UserServiceImpl(UserRepository userRepository) { this.repository = userRepository; } /** {@inheritDoc} */ @Override public User findByUsrCode(String strCode) throws ServiceException { if (StringUtils.isEmpty(strCode)) { throw new IllegalArgumentException("User's code must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; User user = null; try { tx = session.beginTransaction(); Criterion criterion = Restrictions.and(Restrictions.eq("usrCode", strCode), Restrictions.eq("delKbn", Constants.STATUS_ACTIVE)); Criteria criteria = repository.getCriteria(session, User.class); criteria.add(criterion); List<User> users = repository.findByCriteria(criteria); // Release transaction tx.commit(); if (CollectionUtils.isEmpty(users)) { throw new ObjectNotFoundException("Could not find any user matches with code " + strCode); } if (users.size() > 1) { throw new TooManyObjectsException("Found too many users are matched with code " + strCode); } user = users.get(0); } catch (JDBCConnectionException ex) { if (tx != null) { tx.rollback(); } throw new ConnectionException(ex.getMessage(), ex); } catch (org.hibernate.ObjectNotFoundException ex) { if (tx != null) { tx.rollback(); } throw ex; } catch (HibernateException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("An exception occured while finding a logged in user for name " + strCode, ex); } finally { HibernateSessionManager.closeSession(session); } return user; } }