All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.fryske_akademy.services.AbstractCrudService Maven / Gradle / Ivy

The newest version!
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.fryske_akademy.services;

/*-
 * #%L
 * jpaservices
 * %%
 * Copyright (C) 2018 Fryske Akademy
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

import jakarta.annotation.security.DeclareRoles;
import jakarta.annotation.security.PermitAll;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.Parameter;
import jakarta.persistence.Query;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.metamodel.Metamodel;
import jakarta.transaction.Transactional;
import org.fryske_akademy.jpa.DefaultJpqlBuilder;
import org.fryske_akademy.jpa.EntityInterface;
import org.fryske_akademy.jpa.JpqlBuilder;
import org.fryske_akademy.jpa.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

/**
 * 

* This base class enables you to create crud service beans with minimal effort. All you * have to do is override, implement getEntityManager and annotate with for example * {@literal @}Stateless, {@literal @}Local(Auditing.class, * CrudWriteService.class). You can also just define CDI beans instead of EJB, but * be aware you won't get declarative security then.

*

* Inject the crud interfaces using @Inject where you need them.

*

* This base class declares {@link Transactional} and {@link #EDITORROLE} to * protect write operations, read operations by default support no transactions. * When overriding don't forget transaction and role annotations are not * inherited. If you don't need security, override and use * {@link PermitAll}.

*

* A {@link JpqlBuilder} is injected and used for building dynamic queries and * for setting values when using named queries. * * @author eduard */ @DeclareRoles("editor") @Transactional(Transactional.TxType.NOT_SUPPORTED) public abstract class AbstractCrudService implements CrudWriteService, CrudReadService { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractCrudService.class.getName()); /** * default page size (max results), used when no maximum is given. */ public static final int DEFAULT_PAGE_SIZE = 30; public static final String EDITORROLE = "editor"; private JpqlBuilder jpqlBuilder; @Override public T find(Serializable id, Class type) { return getEntityManager().find(type, id); } @Override public List findAll(Class type) { return list(all(type),type); } private TypedQuery all(Class type) { CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(type)); return getEntityManager().createQuery(cq); } private List list(Query q, Class type) { return q.getResultList(); } private Stream stream(Query q, Class type) { return q.getResultStream(); } @Override public List findDynamic(Integer first, Integer max, Map sort, List params, Class type) { return list(dyn(first, max, sort, params, type),type); } private String getEntityName(Class type) { Metamodel model = getEntityManager().getEntityManagerFactory().getMetamodel(); return model.entity(type).getName(); } private TypedQuery dyn(Integer first, Integer max, Map sort, List params, Class type) { String jpql = "from " + getEntityName(type) + " e" + jpqlBuilder.whereClause(params) + jpqlBuilder.orderClause(sort); if (LOGGER.isDebugEnabled()) { LOGGER.debug(jpql); } TypedQuery q = getEntityManager().createQuery(jpql, type); jpqlBuilder.setWhereParams(q, params); q.setFirstResult(first == null ? 0 : first); if (!(max != null && max < 0)) { q.setMaxResults(max == null ? getDefaultPageSize() : max); } return q; } @Override public int countDynamic(List params, Class type) { String jpql = "select count(e) from " + getEntityName(type) + " e" + jpqlBuilder.whereClause(params); if (LOGGER.isDebugEnabled()) { LOGGER.debug(jpql); } return doCount(getEntityManager().createQuery(jpql, Long.class), params); } @Override public List find(String namedQuery, List params, Integer first, Integer max, Class type) { return doFind(getEntityManager().createNamedQuery(namedQuery, type), params, first, max); } @Override public List findNative(String namedNativeQuery, List params, Integer first, Integer max, Class type) { return doFind(getEntityManager().createNamedQuery(namedNativeQuery), params, first, max); } @Override public int count(String namedQuery, List params) { return doCount(getEntityManager().createNamedQuery(namedQuery), params); } /** * * @return {@link #DEFAULT_PAGE_SIZE} */ @Override public int getDefaultPageSize() { return DEFAULT_PAGE_SIZE; } private T findOne(String namedQuery, List params, Class type, boolean exactly) { TypedQuery q = getEntityManager().createNamedQuery(namedQuery, type); jpqlBuilder.setWhereParams(q, params); try { return q.getSingleResult(); } catch (NoResultException e) { if (exactly) throw new PreventEJBLoggingException(e); else return null; } } @Override public T findOne(String namedQuery, List params, Class type) { return findOne(namedQuery,params,type,false); } @Override public T findExactlyOne(String namedQuery, List params, Class type) throws PreventEJBLoggingException { return findOne(namedQuery,params,type,true); } /** * possibly unsafe * @param jpql * @param clazz * @return * @param */ @Override public List findJpql(String jpql, Class clazz) { return getEntityManager().createQuery(jpql,clazz).getResultList(); } /** * possibly unsafe * @param sql * @param clazz * @return * @param */ @Override public List findNative(String sql, Class clazz) { return getEntityManager().createNativeQuery(sql,clazz).getResultList(); } /** * possibly unsafe * * @param sql * @return */ @Override public List findNative(String sql) { return getEntityManager().createNativeQuery(sql).getResultList(); } /** * When overriding look into roles to use, these are not inherited. If you * don't need security, override and use {@link PermitAll}. * * @param * @param t * @return */ @Transactional @Override @RolesAllowed(value = {EDITORROLE}) public T create(T t) { getEntityManager().persist(t); return t; } /** * When overriding look into roles to use, these are not inherited. If you * don't need security, override and use {@link PermitAll}. * * @param * @param t * @return */ @Transactional @Override @RolesAllowed(value = {EDITORROLE}) public T save(T t) { if (t.isTransient()) { return create(t); } else { return update(t); } } /** * * When overriding look into roles to use, these are not inherited. If you * don't need security, override and use {@link PermitAll}. * * @param * @param t * @return */ @Transactional @Override @RolesAllowed(value = {EDITORROLE}) public T update(T t) { return getEntityManager().merge(t); } /** * When overriding look into roles to use, these are not inherited. If you * don't need security, override and use {@link PermitAll}. * * @param t */ @Transactional @Override @RolesAllowed(value = {EDITORROLE}) public void delete(EntityInterface t) { getEntityManager().remove(getEntityManager().find(t.getClass(), t.getId())); } @Transactional @Override @RolesAllowed(value = {EDITORROLE}) public Stream batchSave(Collection entities, Integer flushCount) { final AtomicInteger i = new AtomicInteger(); List r = new ArrayList<>(entities.size()); for (T t : entities) { if (flushCount != null && i.incrementAndGet() % flushCount == 0) { getEntityManager().flush(); } r.add(save(t)); } return r.stream(); } @Transactional @Override @RolesAllowed(value = {EDITORROLE}) public int batchDelete(Collection entities, Integer flushCount) { EntityManager em = getEntityManager(); int i = 0; for (EntityInterface t : entities) { em.remove(em.merge(t)); if (flushCount != null && ++i % flushCount == 0) { em.flush(); } } return i; } @Override public Stream streamAll(Class type) { return stream(all(type),type); } @Override public Stream streamDynamic(Integer first, Integer max, Map sort, List params, Class type) { return stream(dyn(first, max, sort, params,type),type); } @Override public Stream stream(String namedQuery, List params, Integer first, Integer max, Class type) { return doStream(getEntityManager().createNamedQuery(namedQuery), params, first, max); } @Override public Stream streamNative(String namedNativeQuery, List params, Integer first, Integer max, Class type) { return doStream(getEntityManager().createNamedQuery(namedNativeQuery), params, first, max); } @Transactional @Override @RolesAllowed(value = {EDITORROLE}) public T refresh(T t) { getEntityManager().refresh(t); return t; } private List doFind(Query q, List params, Integer first, Integer max) { return findQuery(q, params, first, max).getResultList(); } private Query findQuery(Query q, List params, Integer first, Integer max) { // check number of parameters match Set> parameters = q.getParameters(); if (parameters!=null&¶ms!=null&¶meters.size()!=params.size()) { LOGGER.warn(String.format( "number of parameters in query: %d differs from number of supplied parameters: %d. Possibly" + " due to syntax support in Param for dynamic queries." ,parameters.size(),params.size() )); } jpqlBuilder.setWhereParams(q, params); if (params!=null&¶ms.stream().anyMatch((t) -> t.getNot().equals(" NOT "))) { LOGGER.warn("negations in value (!) not supported for named queries!"); } q.setFirstResult(first == null ? 0 : first); if (max != null) { if (max >= 0) { q.setMaxResults(max); } } else { q.setMaxResults(getDefaultPageSize()); } return q; } private Stream doStream(Query q, List params, Integer first, Integer max) { return findQuery(q, params, first, max).getResultStream(); } private int doCount(Query q, List params) { jpqlBuilder.setWhereParams(q, params); return Integer.parseInt(String.valueOf(q.getSingleResult())); } /** * override to inject your own version of JpqlBuilder * * @param jpqlBuilder */ @Inject protected void setJpqlBuilder(@DefaultJpqlBuilder JpqlBuilder jpqlBuilder) { this.jpqlBuilder = jpqlBuilder; } protected JpqlBuilder getJpqlBuilder() { return jpqlBuilder; } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy