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 org.apache.commons.lang.StringUtils; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.exception.JDBCConnectionException; import com.nec.core.exception.ObjectNotFoundException; import com.nec.crud.hibernate.HibernateSessionManager; import com.nec.harvest.exception.ConnectionException; import com.nec.harvest.exception.ServiceException; import com.nec.harvest.model.Message; import com.nec.harvest.repository.MessageRepository; import com.nec.harvest.service.MessageService; /** * {@link MessageService} * * @author sondn * */ public class MessageServiceImpl implements MessageService { private MessageRepository repository; public MessageServiceImpl(MessageRepository messageRepository) { this.repository = messageRepository; } /** {@inheritDoc} */ @Override public Message findByMsgCode(String msgCode) throws ServiceException { if (StringUtils.isEmpty(msgCode)) { throw new IllegalArgumentException("Message's Id must not be null or empty"); } final Session session = HibernateSessionManager.getSession(); Transaction tx = null; Message message = null; try { tx = session.beginTransaction(); message = repository.get(session, msgCode); // Release transaction tx.commit(); if (message == null) { throw new ObjectNotFoundException("Could not found any message matches with Id " + msgCode); } } catch (JDBCConnectionException ex) { if (tx != null) { tx.rollback(); } throw new ConnectionException( "Database access problem. Killing off all remaining connections in the connection pool.", ex); } catch (HibernateException ex) { if (tx != null) { tx.rollback(); } throw new ServiceException("Could not find any message matches with code " + msgCode, ex); } finally { HibernateSessionManager.closeSession(session); } return message; } }