Bulk inserts in jpa without hibernate

1

Good afternoon everyone, I'm with a project for the faculty that deals with money loans. I'm working with the JPA API. (WITHOUT HIBERNATE)

I have a problem with the response times of the application as the number of entities to persist grows, the greater the number of entities the longer it takes to persist.

The inconvenience occurs when registering a loan with a high amount of fees for example: 96 installments, it takes more than 30 seconds to impact the database.

This is the method that grants a loan. It is defined in the managedBean PrestamoController of type Request.

 public void otorgarPrestamo() {
    try {
        //Establecemos el estado de cuota como impaga;
        Estadocuota ec = new Estadocuota(2);
        //Aqui si lo tiene al cliente
        prestamo.setIdpersona(cliente);

        prestamo.setIdestadoprestamo(estadoPrestamo);
        // Aqui empezamos a setear los valores del prestamo
        // para eso le pasamos los valores del bean frances
        prestamo.setMontoprestado(BigDecimal.valueOf(frances.getMontoSolicitado()));
        prestamo.setFechaSolicitud(frances.getFechaSolicitud());
        prestamo.setCantidadCuotas(frances.getPlazo());
        prestamo.setTna(BigDecimal.valueOf(frances.getTasa()));
        prestamo.setGastosAdm(BigDecimal.valueOf(frances.getGo()));
        prestamo.setSeguroVida(BigDecimal.valueOf(frances.getSv()));
        prestamo.setIva(BigDecimal.valueOf(frances.getIv()));
        // Persisito el prestamo
        prestamoFacade.create(prestamo);
        // Deberia crear las cuotas de ese prestamo iterando sobre la lista
        // frances

        List<Frances> coll = frances.getListaFrances();
        //  itero sobre la coleccion de frances
        for (Frances f : coll) { // Esto lo hace muy lento con muchas cuotas
            //  Defino un objeto de tipo cuota
            Cuota c = new Cuota();
            c.setNroCuota(f.getPlazo());
            c.setValorCuota(BigDecimal.valueOf(f.getCuotaTotal()));
            c.setFechaVenc(f.getFechaSolicitud());
            c.setIdestadocuota(ec);
            c.setIdprestamo(prestamo);
            cuotaFacade.create(c);
        }

        JSFUtil.addSuccessMessage(rf.getMensajeArb("info.save"));
        prestamo = new Prestamo();
        estadoPrestamo = new Estadoprestamo();
        //Estadocuota c = new Estadocuota();

    } catch (Exception e) {
        JSFUtil.addErrorMessage(e.getLocalizedMessage());
    }

}

// CuotaFacade

@Stateless

public class CuotaFacade extends AbstractFacade {

@PersistenceContext(unitName = "com.fcastillo_FacilidadesSA_war_1.0-SNAPSHOTPU")
private EntityManager em;

@Override
protected EntityManager getEntityManager() {
    return em;
}

public CuotaFacade() {
    super(Cuota.class);
}

// retorna lista de cuotas
public List<Cuota> getCuotaList() {
    return em.createNamedQuery("Cuota.findAll").getResultList();
}

// Obtener todas las cuotas de un determinado credito
public List<Cuota> buscarPrestamo(int codigoPrestamo) {
    List<Cuota> lista = null;
    String consulta;
    try {
        consulta = "FROM Cuota c WHERE c.idprestamo.idprestamo=?1";
        Query query = em.createQuery(consulta);
        query.setParameter(1, codigoPrestamo);

        lista = query.getResultList();
    } catch (Exception e) {
        throw e;
    }
    return lista;
}

}

// AbstractFacade

import java.util.List;

import javax.persistence.EntityManager;

/ **  *  * @author fcastillo  * / public abstract class AbstractFacade {

private Class<T> entityClass;

public AbstractFacade(Class<T> entityClass) {
    this.entityClass = entityClass;
}

protected abstract EntityManager getEntityManager();

public void create(T entity) {
    getEntityManager().persist(entity);
}

public void edit(T entity) {
    getEntityManager().merge(entity);
}

public void remove(T entity) {
    getEntityManager().remove(getEntityManager().merge(entity));
}

public T find(Object id) {
    return getEntityManager().find(entityClass, id);
}

public List<T> findAll() {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));
    return getEntityManager().createQuery(cq).getResultList();
}

public List<T> findRange(int[] range) {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    cq.select(cq.from(entityClass));
    javax.persistence.Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(range[1] - range[0] + 1);
    q.setFirstResult(range[0]);
    return q.getResultList();
}

public int count() {
    javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
    javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
    cq.select(getEntityManager().getCriteriaBuilder().count(rt));
    javax.persistence.Query q = getEntityManager().createQuery(cq);
    return ((Long) q.getSingleResult()).intValue();
}

}

I know that iterating over the list and persisting entities is wrong, but it is a quick solution that occurred to me.

Please could anyone help me make those inserts with batch processing?

Thank you very much.

Greetings

Edition 1 -

public void otorgarPrestamo() {

UserTransaction tx = (UserTransaction) new InitialContext (). lookup ("java: comp / UserTransaction");         try {

        tx.begin();
        Estadocuota ec = new Estadocuota(2);
        prestamo.setIdpersona(cliente);
        prestamo.setIdestadoprestamo(estadoPrestamo);
        prestamo.setMontoprestado(BigDecimal.valueOf(frances.getMontoSolicitado()));
        prestamo.setFechaSolicitud(frances.getFechaSolicitud());
        prestamo.setCantidadCuotas(frances.getPlazo());
        prestamo.setTna(BigDecimal.valueOf(frances.getTasa()));
        prestamo.setGastosAdm(BigDecimal.valueOf(frances.getGo()));
        prestamo.setSeguroVida(BigDecimal.valueOf(frances.getSv()));
        prestamo.setIva(BigDecimal.valueOf(frances.getIv()));
        prestamoFacade.create(prestamo);
        List<Frances> coll = frances.getListaFrances();

        for (Frances f : coll) {

            Cuota c = new Cuota();
            c.setNroCuota(f.getPlazo());
            c.setValorCuota(BigDecimal.valueOf(f.getCuotaTotal()));
            c.setFechaVenc(f.getFechaSolicitud());
            c.setIdestadocuota(ec);
            c.setIdprestamo(prestamo);
            cuotaFacade.create(c);

        }
        tx.commit();

        JSFUtil.addSuccessMessage(rf.getMensajeArb("info.save"));
        prestamo = new Prestamo();
        estadoPrestamo = new Estadoprestamo();
        //Estadocuota c = new Estadocuota();

    } catch (Exception e) {
       if(tx!=null){
tx.rollback();
        }
        JSFUtil.addErrorMessage(e.getLocalizedMessage());
    }

}
    
asked by francisco castillo 04.06.2017 в 23:59
source

0 answers