| /** |
| ****************************************************************************** |
| * Copyright © 2017-2018 PTA GmbH. |
| * All rights reserved. This program and the accompanying materials |
| * are made available under the terms of the Eclipse Public License v1.0 |
| * which accompanies this distribution, and is available at |
| * |
| * http://www.eclipse.org/legal/epl-v10.html |
| * |
| ****************************************************************************** |
| */ |
| package org.eclipse.openk.elogbook.persistence.dao; |
| |
| import org.apache.log4j.Logger; |
| import org.apache.log4j.xml.DOMConfigurator; |
| import org.eclipse.openk.elogbook.persistence.dao.interfaces.IGenericDao; |
| |
| import javax.persistence.EntityManager; |
| import javax.persistence.EntityNotFoundException; |
| import javax.persistence.Query; |
| import java.io.Serializable; |
| import java.lang.reflect.Method; |
| import java.lang.reflect.ParameterizedType; |
| import java.util.ArrayList; |
| import java.util.List; |
| |
| /** |
| * @param <T> - persistent Class. |
| * @param <I> - primary Key. |
| * @author Training. |
| */ |
| public abstract class GenericDaoJpa<T, I extends Serializable> implements IGenericDao<T, I> { |
| |
| public static final Logger LOGGER = Logger.getLogger(GenericDaoJpa.class.getName()); |
| |
| // Create Entity Manager Factory |
| private EntityManager em = null; |
| |
| @Override |
| public synchronized EntityManager getEM() { |
| if (em == null) { |
| em = EntityHelper.getEMF().createEntityManager(); |
| } |
| return em; |
| } |
| |
| /** |
| * Standard Constructor. |
| */ |
| public GenericDaoJpa() { |
| DOMConfigurator.configureAndWatch("log4j.xml"); |
| } |
| |
| /** |
| * Set EntityManager from View (OSIV). |
| * |
| * @param em - EntityManager. |
| */ |
| public GenericDaoJpa(EntityManager em) { |
| super(); |
| if (this.em == null) { |
| this.em = em; |
| } |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public T findByIdInTx(final Class<T> persistentClass, final I id) { |
| return getEM().find(persistentClass, id); |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public T findById(final Class<T> persistentClass, final I id) { |
| getEM().getTransaction().begin(); |
| try { |
| final T entity = getEM().find(persistentClass, id); |
| |
| getEM().getTransaction().commit(); |
| |
| return entity; |
| } catch (Exception e) { |
| getEM().getTransaction().rollback(); |
| throw e; |
| } |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public void remove(final T entity, final I id) throws Exception { |
| getEM(); |
| try { |
| em.getTransaction().begin(); |
| em.find(entity.getClass(), id); |
| em.remove(entity); |
| em.getTransaction().commit(); |
| LOGGER.debug("Entity with Id " + id + " removed!"); |
| } catch (EntityNotFoundException ex) { |
| String errorText = "Entity " + entity.toString() + " with id " + id + " no longer exists! - " + ex.getMessage(); //NOSONAR |
| LOGGER.error(errorText); |
| throw new Exception(errorText); |
| } catch (Exception ex) { |
| em.getTransaction().rollback(); |
| String errorText = "Error removing " + entity + "; " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); |
| } finally { |
| LOGGER.debug("GenericDao.remove.finally"); |
| em.close(); |
| } |
| } |
| |
| private void removeInTxInner(final T entity, final I id) throws Exception { |
| try { |
| em.getReference(entity.getClass(), id); |
| } catch (EntityNotFoundException ex) { |
| String errorText = "Entity " + entity.toString() + " with id " + id + " no longer exists! - " + ex.getMessage(); |
| LOGGER.error(errorText); |
| throw new Exception(errorText); |
| } |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public void removeInTx(final T entity, final I id) throws Exception { |
| getEM(); |
| try { |
| this.removeInTxInner(entity, id); |
| em.remove(entity); |
| LOGGER.debug("Entity with Id " + id + " removed!"); |
| } catch (Exception ex) { |
| String errorText = "Error removing " + entity + "; " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); |
| } |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @SuppressWarnings("unchecked") |
| @Override |
| public List<T> find(final boolean all, final int maxResult, |
| final int firstResult) { |
| List<T> entityList; |
| // Returns the persistent class associated wit T. |
| Class<T> persistentClass = getPersistentClass(); |
| String persistentClassName = persistentClass.getSimpleName(); |
| String selectString = "select t from " + persistentClassName + " t"; |
| Query q = em.createQuery(selectString); |
| if (!all) { |
| q.setMaxResults(maxResult); |
| q.setFirstResult(firstResult); |
| } |
| entityList = (List<T>) q.getResultList(); |
| LOGGER.debug("EntityList with " + entityList.size() + " entries found!"); |
| em.close(); |
| return entityList; |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @SuppressWarnings("unchecked") |
| @Override |
| public List<T> findInTx(final boolean all, final int maxResult, |
| final int firstResult) { |
| List<T> entityList; |
| // Returns the persistent class associated wit T. |
| Class<T> persistentClass = getPersistentClass(); |
| String persistentClassName = persistentClass.getSimpleName(); |
| String selectString = "from " + persistentClassName + " t"; |
| Query q = em.createQuery(selectString); |
| if (!all) { |
| q.setMaxResults(maxResult); |
| q.setFirstResult(firstResult); |
| } |
| entityList = (List<T>) q.getResultList(); |
| LOGGER.debug("EntityList with " + entityList.size() + " entries found!"); |
| return entityList; |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public T store(final T entity) throws Exception { |
| T entityNew = null; |
| |
| if (isInsert(entity)) { |
| persist(entity); |
| } else { |
| entityNew = merge(entity); |
| } |
| return entityNew; |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public T storeInTx(final T entity) throws Exception { |
| T entityNew = null; |
| |
| if (isInsert(entity)) { |
| persistInTx(entity); |
| } else { |
| entityNew = mergeInTx(entity); |
| } |
| return entityNew; |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public void persist(final T entity) throws Exception { |
| |
| getEM(); |
| try { |
| em.getTransaction().begin(); |
| em.persist(entity); |
| em.flush(); |
| em.refresh(entity); |
| em.getTransaction().commit(); |
| LOGGER.debug("Entity " + entity + " persisted!"); |
| } catch (Exception ex) { |
| em.getTransaction().rollback(); |
| String errorText = "Error persisting " + entity + ": " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); |
| } finally { |
| LOGGER.debug("GenericDao.persist.finally"); |
| em.close(); |
| } |
| |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public void persistInTx(final T entity) throws Exception { |
| getEM(); |
| try { |
| em.persist(entity); |
| em.flush(); |
| em.refresh(entity); |
| LOGGER.debug("Entity " + entity + " persisted!"); |
| } catch (Exception ex) { |
| String errorText = "Error persisting in Transaction " + entity + ": " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); |
| } |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public T merge(final T entity) throws Exception { |
| getEM(); |
| T entityMerged; |
| try { |
| em.getTransaction().begin(); |
| entityMerged = em.merge(entity); |
| em.getTransaction().commit(); |
| LOGGER.debug("Entity " + entity + " merged!"); |
| } catch (Exception ex) { |
| em.getTransaction().rollback(); |
| String errorText = "Error merging " + entity + ": " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); |
| } finally { |
| LOGGER.debug("GenericDao.merge.finally"); |
| em.close(); |
| } |
| |
| return entityMerged; |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public T mergeInTx(final T entity) throws Exception { |
| getEM(); |
| T entityMerged; |
| try { |
| entityMerged = em.merge(entity); |
| LOGGER.debug("Entity " + entity + " merged!"); |
| } catch (Exception ex) { |
| String errorText = "Error merging in Transaction " + entity + ": " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); |
| } |
| return entityMerged; |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public void startTransaction() { |
| getEM(); |
| em.getTransaction().begin(); |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public void commitTransaction() { |
| getEM(); |
| em.getTransaction().commit(); |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public void rollbackTransaction() { |
| getEM(); |
| em.getTransaction().rollback(); |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public void endTransaction() { |
| getEM(); |
| em.getTransaction().begin(); |
| } |
| |
| /** |
| * {@inheritDoc} |
| */ |
| @Override |
| public void closeSession() { |
| getEM(); |
| em.close(); |
| } |
| |
| /** |
| * Get persistent Class from Parameter. |
| * |
| * @return Class<T> - persistent Class. |
| */ |
| private Class<T> getPersistentClass() { |
| @SuppressWarnings("unchecked") |
| Class<T> persistentClass = (Class<T>) ((ParameterizedType) getClass(). |
| getGenericSuperclass()).getActualTypeArguments()[0]; |
| return persistentClass; |
| } |
| |
| /** |
| * Check for insert or update. |
| * If id == 0, Insert, else Update. |
| * |
| * @param entity T - concrete Enbtity. |
| * @return boolean - true is insert, false is update. |
| * @throws Exception ex. |
| */ |
| @SuppressWarnings({"rawtypes", "unchecked"}) |
| private boolean isInsert(final T entity) throws Exception { |
| |
| Class[] noparams = {}; |
| Object[] noObjParams = {}; |
| Class<T> persistentClass = (Class<T>) entity.getClass(); |
| Method m = persistentClass.getDeclaredMethod("getId", noparams); |
| Integer result = (Integer) m.invoke(entity, noObjParams); |
| return result == null; |
| } |
| |
| /** |
| * Refresh all entities of a collections and reload them from DB |
| * |
| * @param modelCollection List<T> - collection to be refreshed |
| * @return List<T> - refreshed collection |
| */ |
| public List<T> refreshModelCollection(List<T> modelCollection) { |
| List<T> result = new ArrayList<T>(); |
| if (modelCollection != null && !modelCollection.isEmpty()) { |
| em.getEntityManagerFactory().getCache().evict(modelCollection.get(0).getClass()); |
| T mergedEntity; |
| for (T entity : modelCollection) { |
| mergedEntity = em.merge(entity); |
| em.refresh(mergedEntity); |
| result.add(mergedEntity); |
| } |
| } |
| return result; |
| } |
| } |