| /* |
| ******************************************************************************* |
| * Copyright (c) 2018 Contributors to the Eclipse Foundation |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License v. 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0. |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ******************************************************************************* |
| */ |
| |
| package org.eclipse.openk.db.dao; |
| |
| import java.io.Serializable; |
| import java.lang.reflect.Method; |
| import java.lang.reflect.ParameterizedType; |
| import java.util.ArrayList; |
| import java.util.List; |
| import javax.persistence.EntityManager; |
| import javax.persistence.EntityNotFoundException; |
| import javax.persistence.Query; |
| |
| import org.apache.commons.lang.NotImplementedException; |
| import org.apache.log4j.Logger; |
| import org.apache.log4j.xml.DOMConfigurator; |
| import org.eclipse.openk.db.dao.interfaces.IGenericDao; |
| |
| |
| 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; |
| |
| public GenericDaoJpa() { |
| DOMConfigurator.configureAndWatch("log4j.xml"); |
| } |
| |
| public GenericDaoJpa(EntityManager em) { |
| super(); |
| if (this.em == null) { |
| this.em = em; |
| } |
| } |
| |
| @Override |
| public synchronized EntityManager getEM() { |
| if (em == null) { |
| em = EntityHelper.getEMF().createEntityManager(); |
| } |
| return em; |
| } |
| |
| @Override |
| public T findByIdInTx(final Class<T> persistentClass, final I id) { |
| return getEM().find(persistentClass, id); |
| } |
| |
| @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; |
| } |
| } |
| |
| @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.info("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); // NOSONAR _fd Legacy Code! Don't touch! |
| } catch (Exception ex) { |
| em.getTransaction().rollback(); |
| String errorText = "Error removing " + entity + "; " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); // NOSONAR _fd Legacy Code! Don't touch! |
| } finally { |
| LOGGER.info("GenericDao.remove.finally"); |
| em.close(); |
| } |
| } |
| |
| private void removeInTxInner(final T entity, final I id) throws Exception { // NOSONAR _fd Legacy Code! Don't touch! |
| 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); // NOSONAR _fd Legacy Code! Don't touch! |
| } |
| } |
| |
| @Override |
| public void removeInTx(final T entity, final I id) throws Exception { |
| getEM(); |
| try { |
| this.removeInTxInner(entity, id); |
| em.remove(entity); |
| LOGGER.info("Entity with Id " + id + " removed!"); |
| } catch (Exception ex) { |
| String errorText = "Error removing " + entity + "; " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); // NOSONAR _fd Legacy Code! Don't touch! |
| } |
| } |
| |
| @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.info("EntityList with " + entityList.size() + " entries found!"); |
| em.close(); |
| return entityList; |
| } |
| |
| @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.info("EntityList with " + entityList.size() + " entries found!"); |
| return entityList; |
| } |
| |
| @Override |
| public T store(final T entity) throws Exception { |
| T entityNew = null; |
| |
| if (isInsert(entity)) { |
| persist(entity); |
| } else { |
| entityNew = merge(entity); |
| } |
| return entityNew; |
| } |
| |
| @Override |
| public T storeInTx(final T entity) throws Exception { |
| T entityNew; |
| |
| if (isInsert(entity)) { |
| entityNew = persistInTx(entity); |
| } else { |
| entityNew = mergeInTx(entity); |
| } |
| return entityNew; |
| } |
| |
| @Override |
| public T persist(final T entity) throws Exception { |
| |
| getEM(); |
| try { |
| em.getTransaction().begin(); |
| em.persist(entity); |
| em.flush(); |
| em.refresh(entity); |
| em.getTransaction().commit(); |
| LOGGER.info("Entity " + entity + " persisted!"); |
| return entity; |
| } catch (Exception ex) { |
| em.getTransaction().rollback(); |
| String errorText = "Error persisting " + entity + ": " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); // NOSONAR _fd Legacy Code! Don't touch! |
| } finally { |
| LOGGER.info("GenericDao.persist.finally"); |
| em.close(); |
| } |
| |
| } |
| |
| @Override |
| public T persistInTx(final T entity) throws Exception { |
| getEM(); |
| try { |
| em.persist(entity); |
| em.flush(); |
| em.refresh(entity); |
| LOGGER.info("Entity " + entity + " persisted!"); |
| return entity; |
| } catch (Exception ex) { |
| String errorText = "Error persisting in Transaction " + entity + ": " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); // NOSONAR _fd Legacy Code! Don't touch! |
| } |
| } |
| |
| @Override |
| public T merge(final T entity) throws Exception { |
| getEM(); |
| T entityMerged; |
| try { |
| em.getTransaction().begin(); |
| entityMerged = em.merge(entity); |
| em.getTransaction().commit(); |
| LOGGER.info("Entity " + entity + " merged!"); |
| } catch (Exception ex) { |
| em.getTransaction().rollback(); |
| String errorText = "Error merging " + entity + ": " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); // NOSONAR _fd Legacy Code! Don't touch! |
| } finally { |
| LOGGER.info("GenericDao.merge.finally"); |
| em.close(); |
| } |
| |
| return entityMerged; |
| } |
| |
| @Override |
| public T mergeInTx(final T entity) throws Exception { |
| getEM(); |
| T entityMerged; |
| try { |
| entityMerged = em.merge(entity); |
| LOGGER.info("Entity " + entity + " merged!"); |
| } catch (Exception ex) { |
| String errorText = "Error merging in Transaction " + entity + ": " + ex.getMessage(); |
| LOGGER.error(errorText, ex); |
| throw new Exception(errorText); // NOSONAR _fd Legacy Code! Don't touch! |
| } |
| return entityMerged; |
| } |
| |
| @Override |
| public void startTransaction() { |
| getEM(); |
| em.getTransaction().begin(); |
| } |
| |
| @Override |
| public void commitTransaction() { |
| getEM(); |
| em.getTransaction().commit(); |
| } |
| |
| @Override |
| public void rollbackTransaction() { |
| getEM(); |
| em.getTransaction().rollback(); |
| } |
| |
| |
| @Override |
| public void endTransaction() { |
| throw new NotImplementedException(); |
| } |
| |
| |
| @Override |
| public void closeSession() { |
| getEM(); |
| em.close(); |
| } |
| |
| |
| private Class<T> getPersistentClass() { |
| @SuppressWarnings("unchecked") |
| Class<T> persistentClass = (Class<T>) ((ParameterizedType) getClass(). |
| getGenericSuperclass()).getActualTypeArguments()[0]; |
| return persistentClass; |
| } |
| |
| |
| @SuppressWarnings({"rawtypes", "unchecked"}) |
| private boolean isInsert(final T entity) throws Exception { // NOSONAR _fd Legacy Code! Don't touch! |
| |
| 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; |
| } |
| |
| public List<T> refreshModelCollection(List<T> modelCollection) { |
| List<T> result = new ArrayList<>(); |
| 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; |
| } |
| } |