org.fryske_akademy.ejb.AbstractCrudService Maven / Gradle / Ivy
/*
* 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.ejb;
/*-
* #%L
* ejbCrudApi
* %%
* 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 org.fryske_akademy.jpa.JpqlBuilder;
import org.fryske_akademy.jpa.Param;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.TransactionAttribute;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.transaction.Transactional;
import org.fryske_akademy.jpa.EntityInterface;
import org.fryske_akademy.jpa.JpqlBuilderImpl;
/**
*
* This base class enables you to create minimal crud service beans. All you
* have to do is override, implement getEntityManager and annotate with
*
* @Stateless, @Local(CrudReadService.class, CrudWriteService.class).
*
* Inject the crud interfaces using @Inject where you need them.
*
* This base class declares {@link Transactional} and {@link #EDITORROLE} to
* protect write operations. 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 JpqlBuilderImpl} is used for building where and order by clauses in
* dynamic queries, i.e. used in null {@link #findDynamic(java.lang.Integer, java.lang.Integer, java.util.Map, java.util.List, java.lang.Class)
* }.
* The JpqlBuilder is also used for setting parameter values.
*
* @author eduard
*/
@DeclareRoles("editor")
public abstract class AbstractCrudService implements CrudWriteService {
private JpqlBuilder jpqlBuilder;
private static final Logger LOGGER = Logger.getLogger(AbstractCrudService.class.getName());
protected abstract EntityManager getEntityManager();
@Override
public T find(Serializable id, Class type) {
return getEntityManager().find(type, id);
}
@Override
public List findAll(Class type) {
CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(type));
return getEntityManager().createQuery(cq).getResultList();
}
/**
*
* @param
* @param first defaults to 0
* @param pageSize defaults to {@link #DEFAULT_PAGE_SIZE}, negative value
* means no limit
* @param sort
* @param params
* @param type
* @return
*/
@Override
public List findDynamic(Integer first, Integer pageSize, Map sort, List params, Class type) {
String jpql = "from " + type.getSimpleName() + " e" + jpqlBuilder.whereClause(params) + jpqlBuilder.orderClause(sort);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine(jpql);
}
TypedQuery q = getEntityManager().createQuery(jpql, type);
jpqlBuilder.setWhereParams(q, params);
q.setFirstResult(first == null ? 0 : first);
if (!(pageSize != null && pageSize < 0)) {
q.setMaxResults(pageSize == null ? DEFAULT_PAGE_SIZE : pageSize);
}
return (List) q.getResultList();
}
@Override
public int countDynamic(List params, Class type) {
String jpql = "select count(*) from " + type.getSimpleName() + " e" + jpqlBuilder.whereClause(params);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine(jpql);
}
return doCount(getEntityManager().createQuery(jpql, Long.class), params);
}
/**
*
* @param
* @param namedQuery
* @param params
* @param first defaults to 0
* @param max defaults to {@link #DEFAULT_PAGE_SIZE}, negative value means
* no limit
* @param type
* @return
*/
@Override
public List find(String namedQuery, List params, Integer first, Integer max, Class type) {
return doFind(getEntityManager().createNamedQuery(namedQuery, type), params, first, max);
}
/**
*
* @param
* @param namedNativeQuery
* @param params
* @param first
* @param max defaults to {@link #DEFAULT_PAGE_SIZE}, negative value means
* no limit
* @param type
* @return
*/
@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);
}
/**
* default page size (max results), used when no maximum is given.
*/
public static final int DEFAULT_PAGE_SIZE = 30;
@Override
public T findOne(String namedQuery, List params, Class type) {
TypedQuery q = getEntityManager().createNamedQuery(namedQuery, type);
jpqlBuilder.setWhereParams(q, params);
try {
return q.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
public static final String EDITORROLE = "editor";
/**
* When overriding look into {@link Transactional} and 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;
}
/**
* create or update depending on {@link EntityInterface#isTransient() }.
* @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 {@link Transactional} and 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 {@link Transactional} and roles to use, these
* are not inherited. If you don't need security, override and use
* {@link PermitAll}.
*
* @param t
*/
@Transactional
@TransactionAttribute
@Override
@RolesAllowed(value = {EDITORROLE})
public void delete(EntityInterface t) {
getEntityManager().remove(getEntityManager().find(t.getClass(), t.getId()));
}
/**
* updates multiple entities, when flushCount != null flushes and clears the entitymanager every flushCount entities.
* NOTE that this method executes in one (possibly big) sql transaction!
* @param t
* @param flushCount
* @return the number of entities updated
*/
@Transactional
@TransactionAttribute
@Override
@RolesAllowed(value = {EDITORROLE})
public Stream batchSave(Collection entities, Integer flushCount) {
EntityManager em = getEntityManager();
int i = 0;
List l = new ArrayList<>(entities.size());
for (T t : entities) {
if (t.isTransient()) {
em.persist(t);
l.add(t);
} else {
l.add(em.merge(t));
}
if (flushCount != null && ++i % flushCount == 0) {
em.flush();
em.clear();
}
}
return l.stream();
}
/**
* deletes multiple entities, when flushCount != null flushes and clears the entitymanager every flushCount entities.
* NOTE that this method executes in one (possibly big) sql transaction!
* @param t
* @param flushCount
* @return the number of entities deleted
*/
@Transactional
@TransactionAttribute
@Override
@RolesAllowed(value = {EDITORROLE})
public int batchDelete(Collection extends EntityInterface> t, Integer flushCount) {
EntityManager em = getEntityManager();
AtomicInteger i = new AtomicInteger();
t.forEach((e) -> {
em.remove(em.merge(e));
int inc = i.incrementAndGet();
if (flushCount != null && inc % flushCount == 0) {
em.flush();
em.clear();
}
});
return i.get();
}
private List doFind(Query q, List params, Integer first, Integer max) {
jpqlBuilder.setWhereParams(q, params);
q.setFirstResult(first == null ? 0 : first);
if (max != null) {
if (max >= 0) {
q.setMaxResults(max);
}
} else {
q.setMaxResults(DEFAULT_PAGE_SIZE);
}
return q.getResultList();
}
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(JpqlBuilder jpqlBuilder) {
this.jpqlBuilder = jpqlBuilder;
}
}