Example usage for javax.persistence TypedQuery getSingleResult

List of usage examples for javax.persistence TypedQuery getSingleResult

Introduction

In this page you can find the example usage for javax.persistence TypedQuery getSingleResult.

Prototype

X getSingleResult();

Source Link

Document

Execute a SELECT query that returns a single result.

Usage

From source file:org.easy.criteria.CriteriaProcessor.java

/**
 * Finds a single entity for the given criteria. This ignores the "Select"
 * clause of CriteriaContainer. If you need to selected some specific
 * columns//from   ww  w  .j  a v a 2s.  c o  m
 * then use "findUniqueTuple" API.
 * 
 * @param criteria
 * @param lockMode
 *            - Pass NULL if your are not managing transaction.
 *            LockModeType.NONE will through exception if no transaction is
 *            active.
 * @return - A single entity or null if no result was found.
 */
public <T> T findUniqueEntity(CriteriaComposer<T> criteria, QueryProperties properties) {
    log.trace("CriteriaProcessor.findUniqueEntity");
    Preconditions.checkNotNull(criteria);

    Class<T> forClass = criteria.getEntityClass();

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(forClass);

    log.debug("root =" + forClass.getName());
    Root<T> root = criteriaQuery.from(forClass);

    List<Predicate> wherePredicates = new ArrayList<Predicate>();

    if (criteria != null) {
        criteria.generateJoins(root);
        criteria.generateWhere(criteriaBuilder, wherePredicates);
    }

    criteriaQuery.where(wherePredicates.toArray(new Predicate[wherePredicates.size()]));

    TypedQuery<T> query = entityManager.createQuery(criteriaQuery);

    if (properties != null)
        properties.applyProperties(query);

    return query.getSingleResult();
}

From source file:org.easy.criteria.CriteriaProcessor.java

/**
 * Finds single tuple for the given criteria. Make sure you have provided
 * columns information in CriteriaContainer that you want in this tuple
 * result-set./*from  www . j a va 2 s. c o m*/
 * 
 * @param criteria
 * @param lockMode
 * @return - A single tuple or null if no result was found.
 */
public <T> Tuple findUniqueTuple(CriteriaComposer<T> criteria, QueryProperties properties) {
    log.trace("CriteriaProcessor.findUniqueTuple");
    Preconditions.checkNotNull(criteria);

    Class<T> forClass = criteria.getEntityClass();

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteriaQuery = criteriaBuilder.createQuery(Tuple.class);

    log.debug("root =" + forClass.getName());
    Root<T> root = criteriaQuery.from(forClass);

    List<Predicate> wherePredicates = new ArrayList<Predicate>();
    List<Selection<?>> selectAttributes = new ArrayList<Selection<?>>();

    if (criteria != null) {
        criteria.generateJoins(root);
        criteria.generateSelect(criteriaBuilder, selectAttributes);
        criteria.generateWhere(criteriaBuilder, wherePredicates);
    }

    Preconditions.checkState(selectAttributes != null);
    Preconditions.checkArgument(selectAttributes.size() > 0, "No column name found for select clause. "
            + "Atleast one should be provided for Tuple result. Consider using findUniqueEntity instead.");

    criteriaQuery.multiselect(selectAttributes);

    criteriaQuery.where(wherePredicates.toArray(new Predicate[wherePredicates.size()]));

    TypedQuery<Tuple> query = entityManager.createQuery(criteriaQuery);

    if (properties != null)
        properties.applyProperties(query);

    return query.getSingleResult();
}

From source file:org.jlgranda.fede.database.SetupService.java

private void validateDB() {
    Setting singleResult = null;//  ww  w  . ja v  a2  s.  c o  m
    try {
        TypedQuery<Setting> query = getEntityManager()
                .createQuery("from Setting s where s.name='schemaVersion'", Setting.class);
        singleResult = query.getSingleResult();
    } catch (NoResultException e) {
        java.util.Date now = Dates.now();
        singleResult = new Setting("schemaVersion", "1");
        singleResult.setCreatedOn(now);
        singleResult.setLastUpdate(now);
        singleResult.setCodeType(CodeType.SYSTEM);
        getEntityManager().persist(singleResult);
        getEntityManager().flush();
    }

    log.info("Current database schema version is [" + singleResult.getValue() + "]");

}

From source file:org.jlgranda.fede.database.SetupService.java

private void validateGroups() {

    Group singleResult = null;//  w ww. j a v a 2s .  c o m
    Map<String, String> props = new HashMap<>();

    //Grupos de arranque del sistema
    props.put("fede", "fede:1");
    props.put("salud", "Salud:2");
    props.put("alimentos", "Alimentos:3");
    props.put("ropa", "Ropa:4");
    props.put("educacion", "Educacin:5");
    props.put("vivienda", "Vivienda:6");

    props.put("favorito", "Favoritos:7");

    String value = null;
    String name = null;
    Short orden = null;
    for (String key : props.keySet()) {
        value = props.get(key);
        try {
            TypedQuery<Group> query = getEntityManager().createQuery("from Group g where g.code='" + key + "'",
                    Group.class);
            singleResult = query.getSingleResult();
        } catch (NoResultException e) {

            java.util.Date now = Dates.now();
            name = value.split(":")[0];
            orden = Short.valueOf(value.split(":")[1]);
            singleResult = new Group(key, name);
            singleResult.setOrden(orden);
            singleResult.setCreatedOn(now);
            singleResult.setLastUpdate(now);
            singleResult.setCodeType(CodeType.TAG);
            singleResult.setStatus(StatusType.ACTIVE.toString());
            getEntityManager().persist(singleResult);
            getEntityManager().flush();
        }

        log.info("Added group code: {} name: [{}]", key, singleResult.getName());
    }
}

From source file:org.jlgranda.fede.database.SetupService.java

private void validateSetting() {

    Setting singleResult = null;//from ww  w .j a  v  a  2 s .  c  om
    Map<String, String> props = new HashMap<>();

    //email settings
    //        props.put("mail.from", "fede@jlgranda.com:Remitente de correo electrnico");
    //        props.put("mail.host", "jlgranda.com:Servidor de correo electrnico");
    //        props.put("mail.user", "fede:Usuario de correo electrnico");
    //        props.put("mail.password", "LieferQuireMidstUpends95: Contrasea de correo electrnico");
    //        props.put("mail.inbox", "INBOX:Carpeta de correo electrnico");
    //        props.put("mail.port", "25:Puerto de correo");
    //        props.put("mail.verbose", "false:Mostrar detalles de conversacin de sessin de correo");
    //        props.put("mail.debug", "false:Mostrar informacin de depuracin de sessin de correo");
    //        
    //        props.put("mail.store.protocol", "imap:Protocolo de sessin de correo");
    //        props.put("mail.transport.protocol", "smtps:Protocolo seguro de sessin de correo");
    props.put("mail.imap.host", "jlgranda.com:Servidor IMAP:IMAP");
    props.put("mail.imap.port", "25:Puerto IMAP:IMAP");
    props.put("mail.imaps.ssl.trust", "*:SSL TRUST:SMTPS");

    props.put("mail.smtps.port", "25:Puerto SMTP:SMTPS");
    props.put("mail.smtps.host", "jlgranda.com:Servidor de envios SMTPS:SMTPS");
    props.put("mail.smtps.from", "AppsVentas <consiguemas@jlgranda.com>:Remitente de correo:SMTPS");
    props.put("mail.smtps.username", "consiguemas@jlgranda.com:SMTP Username:SMTPS");
    props.put("mail.smtps.password", "LitePorePrudePursed13:SMTP Password:SMTPS");
    props.put("mail.smtps.auth", "true:Usar autenticacin:SMTPS");
    props.put("mail.smtps.ssl", "true:SSL:SMTPS");
    props.put("mail.smtp.starttls.enable", "false:Usar TTLS:SMTPS");

    //XML utils settings
    props.put("fede.xml.tag.numeroAutorizacion",
            "<numeroAutorizacion></numeroAutorizacion>:Etiqueta de nmero de autorizacin en XML:XML");
    props.put("fede.xml.tag.fechaAutorizacion",
            "<fechaAutorizacion></fechaAutorizacion>:Etiqueta de fecha de autorizacin en XML:XML");

    //dates patterns
    props.put("fede.date.pattern", "dd/MM/yyyy:Formato de fecha:SYSTEM");

    //UI settings
    props.put("fede.group.default", "fede:Grupo por defecto:UI");
    props.put("fede.dashboard.timeline.length", "10:Longitud de lista en dashboard::UI");
    props.put("fede.dashboard.range", "364:Rango de tiempo para mostrar tablas:UI"); //364 das
    props.put("fede.inbox.list.length", "50:Nmero de filas en detalles tipo tabla:UI"); //50 das
    props.put("app.fede.sales.dashboard.refreshtime", "20:Tiempo de refresco en pantallas de monitoreo:UI"); //20 segundos
    props.put("app.fede.sales.dashboard.lasts.list.length", "10:Longitud de listas rpidas:UI"); //10 segundos
    props.put("app.fede.sizeLimit", "1048576:Tamao mximo de carga de archivo:UI"); //maximo tamao de archivo a subir
    props.put("app.fede.fileLimit", "34:Nmero mximo de archivos a cargar:UI"); //Maximo de archivos a subir
    props.put("app.fede.allowTypes", "/(\\.|\\/)(xml|zip|pdf|txt)$/:Tipos de archivos permitidos:UI"); //Tipo de archivo permitidos
    props.put("app.management.tarea.documentos.sizeLimit", "1048576:Tamao mximo de carga de archivo:UI"); //maximo tamao de archivo a subir
    props.put("app.management.tarea.documentos.fileLimit", "34:Nmero mximo de archivos a cargar:UI"); //Maximo de archivos a subir
    props.put("app.management.tarea.documentos.allowTypes",
            "/(\\.|\\/)(xml|zip|pdf|txt)$/:Tipos de archivos permitidos:UI"); //Tipo de archivo permitidos
    props.put("app.admin.subject.sizeLimit", "1048576:Tamao mximo de carga de archivo:UI"); //maximo tamao de archivo a subir
    props.put("app.admin.subject.fileLimit", "34:Nmero mximo de archivos a cargar:UI"); //Maximo de archivos a subir
    props.put("app.admin.subject.allowTypes", "/(\\.|\\/)(gif|jpe?g|png)$/:Tipos de archivos permitidos:UI"); //Tipo de archivo permitidos
    props.put("app.profile.photo.width", "100:Ancho de Imagen:UI"); //Ancho de imgenes
    props.put("app.profile.photo.height", "100:Alto de Imagen:UI"); //Alto de imgenes

    props.put("app.fede.decimalSeparator", ".:Separador de decimales:CORE");
    props.put("app.fede.thousandSeparator", ",:Separador de miles:CORE");
    props.put("app.fede.decimalPlaces", "2:Nmero de digitos a mostrar en campos tipo nmero:CORE");
    props.put("app.fede.inventory.top", "10:Nmero de elementos en listas top:CORE");

    String label = null;
    String value = null;
    String category = null;
    for (String key : props.keySet()) {
        value = props.get(key).split(":")[0];
        label = props.get(key).split(":")[1];
        category = props.get(key).split(":")[2];
        try {
            TypedQuery<Setting> query = getEntityManager()
                    .createQuery("from Setting s where s.name='" + key + "' and owner is null", Setting.class);
            singleResult = query.getSingleResult();
        } catch (NoResultException e) {
            java.util.Date now = Dates.now();
            singleResult = new Setting(label, key, value);
            singleResult.setCategory(category);
            singleResult.setCreatedOn(now);
            singleResult.setLastUpdate(now);
            singleResult.setCodeType(CodeType.SYSTEM);
            singleResult.setStatus(StatusType.ACTIVE.toString());
            getEntityManager().persist(singleResult);
            getEntityManager().flush();
        }

        log.info("Current  {} is [{}]", key, singleResult.getValue());
    }
}

From source file:org.jlgranda.fede.database.SetupService.java

private void validateSecurity() {
    Subject singleResult = null;/*  w ww.  j  av  a 2 s.c o  m*/
    try {
        TypedQuery<Subject> query = getEntityManager().createQuery("from Subject s where s.username='admin'",
                Subject.class);
        singleResult = query.getSingleResult();
    } catch (NoResultException e) {
        singleResult = createAdministrator();
        getEntityManager().persist(singleResult);
    }
}

From source file:org.jlgranda.fede.database.SetupService.java

private void validateDefaultCustomer() {
    Subject singleResult = null;//from w ww.  j  a  v a  2  s . c o m
    try {
        TypedQuery<Subject> query = getEntityManager()
                .createQuery("from Subject s where s.username='consumidorfinal'", Subject.class);
        singleResult = query.getSingleResult();
    } catch (NoResultException e) {
        singleResult = createDefaultCustomer();
        getEntityManager().persist(singleResult);
    }
}

From source file:org.jlgranda.fede.database.SetupService.java

private void validateDefaultSupplier() {
    Subject singleResult = null;//from  w w  w  .  j  a va2  s .  c  o m
    try {
        TypedQuery<Subject> query = getEntityManager()
                .createQuery("from Subject s where s.username='proveedorsinfactura'", Subject.class);
        singleResult = query.getSingleResult();
    } catch (NoResultException e) {
        singleResult = createDefaultSupplier();
        getEntityManager().persist(singleResult);
    }
}

From source file:org.kie.processmigration.service.impl.MigrationServiceImpl.java

@Override
public Migration get(Long id) throws MigrationNotFoundException {
    TypedQuery<Migration> query = em.createNamedQuery("Migration.findById", Migration.class);
    query.setParameter("id", id);
    try {//from w  ww .  ja  v a 2s.  co  m
        return query.getSingleResult();
    } catch (NoResultException e) {
        throw new MigrationNotFoundException(id);
    }
}

From source file:org.kuali.rice.kew.actiontaken.dao.impl.ActionTakenDaoJpa.java

public Timestamp getLastActionTakenDate(String documentId, ActionType actionType) {
    if (StringUtils.isBlank(documentId) || actionType == null) {
        throw new IllegalArgumentException("Both documentId and actionType must be non-null");
    }/* w  w w. ja  v a 2 s . c o  m*/
    TypedQuery<Timestamp> query = entityManager.createNamedQuery(GET_LAST_ACTION_TAKEN_DATE_NAME,
            Timestamp.class);
    query.setParameter("documentId", documentId);
    query.setParameter("actionTaken", actionType.getCode());
    try {
        return query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}