Example usage for org.hibernate.criterion Restrictions and

List of usage examples for org.hibernate.criterion Restrictions and

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions and.

Prototype

public static LogicalExpression and(Criterion lhs, Criterion rhs) 

Source Link

Document

Return the conjuction of two expressions

Usage

From source file:Compras.reportePedidos.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(usr, 0);
    h.session(sessionPrograma);/* ww w . j a va 2s  .c o m*/
    if (t_datos.getRowCount() > 0) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
        jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.pdf)", new String[] { "pdf" }));
        String ruta = null;
        if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
            ruta = jF1.getSelectedFile().getAbsolutePath();
            if (ruta != null) {
                try {
                    DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.00");
                    formatoPorcentaje.setMinimumFractionDigits(2);
                    session.beginTransaction().begin();
                    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
                            BaseFont.NOT_EMBEDDED);
                    PDF reporte = new PDF();
                    Date fecha = new Date();
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
                    String valor = dateFormat.format(fecha);

                    reporte.Abrir2(PageSize.LETTER.rotate(), "Reporte", ruta + ".pdf");
                    Font font = new Font(Font.FontFamily.HELVETICA, 8, Font.NORMAL);
                    BaseColor contenido = BaseColor.WHITE;
                    int centro = Element.ALIGN_CENTER;
                    int izquierda = Element.ALIGN_LEFT;
                    int derecha = Element.ALIGN_RIGHT;
                    float[] tam_pdf = new float[] { 15, 40, 130, 20, 15, 30, 20, 15 };

                    PdfPTable tabla = reporte.crearTabla(tam_pdf.length, tam_pdf, 100, Element.ALIGN_LEFT);

                    cabeceraReporte(reporte, bf, tabla);
                    Object no[];
                    int ren[];
                    if (t_datos.getSelectedRows().length > 0) {
                        no = new Object[t_datos.getSelectedRows().length];
                        ren = t_datos.getSelectedRows();
                        for (int x = 0; x < t_datos.getSelectedRows().length; x++) {
                            no[x] = (int) t_datos.getValueAt(ren[x], 0);
                        }
                    } else {
                        no = new Object[t_datos.getRowCount()];
                        //ren =new int[t_datos.getRowCount()];
                        for (int x = 0; x < t_datos.getRowCount(); x++) {
                            no[x] = (int) t_datos.getValueAt(x, 0);
                        }
                    }
                    Pedido[] pedidos;
                    if (autorizado.isSelected() == true) {
                        pedidos = (Pedido[]) session.createCriteria(Pedido.class)
                                .add(Restrictions.and(
                                        Restrictions.and(Restrictions.isNotNull("usuarioByAutorizo"),
                                                Restrictions.isNotNull("usuarioByAutorizo2")),
                                        Restrictions.in("idPedido", no)))
                                .list().toArray(new Pedido[0]);
                    } else {
                        pedidos = (Pedido[]) session.createCriteria(Pedido.class)
                                .add(Restrictions.in("idPedido", no)).list().toArray(new Pedido[0]);
                    }
                    if (pedidos.length > 0) {
                        ArrayList ordena = new ArrayList();
                        for (int a = 0; a < pedidos.length; a++) {
                            Pedido aux = pedidos[a];
                            if (aux.getTipoPedido().compareTo("Interno") == 0) {
                                Partida[] par = (Partida[]) aux.getPartidas().toArray(new Partida[0]);
                                for (int b = 0; b < par.length; b++) {
                                    Partida ren1 = par[b];
                                    Renglon nuevo;
                                    if (ren1.getEjemplar() != null)
                                        nuevo = new Renglon("" + aux.getIdPedido(),
                                                ren1.getEjemplar().getIdParte(), ren1.getCatalogo().getNombre(),
                                                ren1.getCantPcp(), ren1.getMed(), ren1.getPcp(),
                                                "" + ren1.getOrdenByIdOrden().getIdOrden(),
                                                "" + ren1.getIdEvaluacion() + "-" + ren1.getSubPartida());
                                    else
                                        nuevo = new Renglon("" + aux.getIdPedido(), "",
                                                ren1.getCatalogo().getNombre(), ren1.getCantPcp(),
                                                ren1.getMed(), ren1.getPcp(),
                                                "" + ren1.getOrdenByIdOrden().getIdOrden(),
                                                "" + ren1.getIdEvaluacion() + "-" + ren1.getSubPartida());
                                    ordena.add(nuevo);
                                }
                            }

                            if (aux.getTipoPedido().compareTo("Externo") == 0) {
                                PartidaExterna[] par = (PartidaExterna[]) aux.getPartidaExternas()
                                        .toArray(new PartidaExterna[0]);
                                for (int b = 0; b < par.length; b++) {
                                    PartidaExterna ren2 = par[b];
                                    Renglon nuevo;
                                    nuevo = new Renglon("" + aux.getIdPedido(), ren2.getNoParte(),
                                            ren2.getDescripcion(), ren2.getCantidad(), ren2.getUnidad(),
                                            ren2.getCosto(), "", "" + "Ext");
                                    ordena.add(nuevo);
                                }
                            }

                            if (aux.getTipoPedido().compareTo("Adicional") == 0) {
                                PartidaExterna[] par = (PartidaExterna[]) aux.getPartidaExternas()
                                        .toArray(new PartidaExterna[0]);
                                for (int b = 0; b < par.length; b++) {
                                    PartidaExterna ren2 = par[b];
                                    Renglon nuevo;
                                    nuevo = new Renglon("" + aux.getIdPedido(), ren2.getNoParte(),
                                            ren2.getDescripcion(), ren2.getCantidad(), ren2.getUnidad(),
                                            ren2.getCosto(), "" + aux.getOrden().getIdOrden(), "ADI");
                                    ordena.add(nuevo);
                                }
                            }
                        }

                        Collections.sort(ordena, new Comparator() {
                            @Override
                            public int compare(Object o1, Object o2) {
                                Renglon p1 = (Renglon) o1;
                                Renglon p2 = (Renglon) o2;
                                return new String(p1.np + p1.descripcion)
                                        .compareTo(new String(p2.np + p2.descripcion));
                            }
                        });

                        for (int c = 0; c < ordena.size(); c++) {
                            Renglon r1 = (Renglon) ordena.get(c);
                            tabla.addCell(reporte.celda(r1.pedido, font, contenido, derecha, 0, 1,
                                    Rectangle.RECTANGLE));
                            tabla.addCell(
                                    reporte.celda(r1.np, font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(r1.descripcion, font, contenido, izquierda, 0, 1,
                                    Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(formatoPorcentaje.format(r1.cant), font, contenido,
                                    derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(
                                    reporte.celda(r1.med, font, contenido, derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(formatoPorcentaje.format(r1.precio), font, contenido,
                                    derecha, 0, 1, Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda("" + r1.orden, font, contenido, centro, 0, 1,
                                    Rectangle.RECTANGLE));
                            tabla.addCell(reporte.celda(r1.partida, font, contenido, derecha, 0, 1,
                                    Rectangle.RECTANGLE));
                        }
                    }

                    tabla.setHeaderRows(2);
                    reporte.agregaObjeto(tabla);
                    reporte.cerrar();
                    reporte.visualizar2(ruta + ".pdf");
                } catch (Exception e) {
                    System.out.println(e);
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this,
                            "No se pudo realizar el reporte si el archivo esta abierto.");
                } finally {
                    if (session != null)
                        if (session.isOpen())
                            session.close();
                }
            }
        }
    }
}

From source file:Compras.reportePedidos.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    // TODO add your handling code here:
    h = new Herramientas(usr, 0);
    h.session(sessionPrograma);//w ww.ja  v  a2s .c om
    if (t_datos.getRowCount() > 0) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        javax.swing.JFileChooser jF1 = new javax.swing.JFileChooser();
        jF1.setFileFilter(new ExtensionFileFilter("Excel document (*.xls)", new String[] { "xls" }));
        String ruta = null;
        if (jF1.showSaveDialog(null) == jF1.APPROVE_OPTION) {
            ruta = jF1.getSelectedFile().getAbsolutePath();
            if (ruta != null) {
                File archivoXLS = new File(ruta + ".xls");
                try {
                    DecimalFormat formatoPorcentaje = new DecimalFormat("#,##0.00");
                    formatoPorcentaje.setMinimumFractionDigits(2);
                    session.beginTransaction().begin();
                    if (archivoXLS.exists())
                        archivoXLS.delete();
                    archivoXLS.createNewFile();
                    Workbook libro = new HSSFWorkbook();
                    FileOutputStream archivo = new FileOutputStream(archivoXLS);
                    Sheet hoja = libro.createSheet("VALUACION");

                    Date fecha = new Date();
                    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyyHH-mm-ss");//YYYY-MM-DD HH:MM:SS
                    String valor = dateFormat.format(fecha);

                    Object no[];
                    int ren[];
                    if (t_datos.getSelectedRows().length > 0) {
                        no = new Object[t_datos.getSelectedRows().length];
                        ren = t_datos.getSelectedRows();
                        for (int x = 0; x < t_datos.getSelectedRows().length; x++) {
                            no[x] = (int) t_datos.getValueAt(ren[x], 0);
                        }
                    } else {
                        no = new Object[t_datos.getRowCount()];
                        //ren =new int[t_datos.getRowCount()];
                        for (int x = 0; x < t_datos.getRowCount(); x++) {
                            no[x] = (int) t_datos.getValueAt(x, 0);
                        }
                    }
                    Pedido[] pedidos;
                    if (autorizado.isSelected() == true) {
                        pedidos = (Pedido[]) session.createCriteria(Pedido.class)
                                .add(Restrictions.and(
                                        Restrictions.and(Restrictions.isNotNull("usuarioByAutorizo"),
                                                Restrictions.isNotNull("usuarioByAutorizo2")),
                                        Restrictions.in("idPedido", no)))
                                .list().toArray(new Pedido[0]);
                    } else {
                        pedidos = (Pedido[]) session.createCriteria(Pedido.class)
                                .add(Restrictions.in("idPedido", no)).list().toArray(new Pedido[0]);
                    }
                    if (pedidos.length > 0) {
                        ArrayList ordena = new ArrayList();
                        for (int a = 0; a < pedidos.length; a++) {
                            Pedido aux = pedidos[a];
                            if (aux.getTipoPedido().compareTo("Interno") == 0) {
                                Partida[] par = (Partida[]) aux.getPartidas().toArray(new Partida[0]);
                                for (int b = 0; b < par.length; b++) {
                                    Partida ren1 = par[b];
                                    Renglon nuevo;
                                    if (ren1.getEjemplar() != null)
                                        nuevo = new Renglon("" + aux.getIdPedido(),
                                                ren1.getEjemplar().getIdParte(), ren1.getCatalogo().getNombre(),
                                                ren1.getCantPcp(), ren1.getMed(), ren1.getPcp(),
                                                "" + ren1.getOrdenByIdOrden().getIdOrden(),
                                                "" + ren1.getIdEvaluacion() + "-" + ren1.getSubPartida());
                                    else
                                        nuevo = new Renglon("" + aux.getIdPedido(), "",
                                                ren1.getCatalogo().getNombre(), ren1.getCantPcp(),
                                                ren1.getMed(), ren1.getPcp(),
                                                "" + ren1.getOrdenByIdOrden().getIdOrden(),
                                                "" + ren1.getIdEvaluacion() + "-" + ren1.getSubPartida());
                                    ordena.add(nuevo);
                                }
                            }

                            if (aux.getTipoPedido().compareTo("Externo") == 0) {
                                PartidaExterna[] par = (PartidaExterna[]) aux.getPartidaExternas()
                                        .toArray(new PartidaExterna[0]);
                                for (int b = 0; b < par.length; b++) {
                                    PartidaExterna ren2 = par[b];
                                    Renglon nuevo;
                                    nuevo = new Renglon("" + aux.getIdPedido(), ren2.getNoParte(),
                                            ren2.getDescripcion(), ren2.getCantidad(), ren2.getUnidad(),
                                            ren2.getCosto(), "", "" + "Ext");
                                    ordena.add(nuevo);
                                }
                            }

                            if (aux.getTipoPedido().compareTo("Adicional") == 0) {
                                PartidaExterna[] par = (PartidaExterna[]) aux.getPartidaExternas()
                                        .toArray(new PartidaExterna[0]);
                                for (int b = 0; b < par.length; b++) {
                                    PartidaExterna ren2 = par[b];
                                    Renglon nuevo;
                                    nuevo = new Renglon("" + aux.getIdPedido(), ren2.getNoParte(),
                                            ren2.getDescripcion(), ren2.getCantidad(), ren2.getUnidad(),
                                            ren2.getCosto(), "" + aux.getOrden().getIdOrden(), "ADI");
                                    ordena.add(nuevo);
                                }
                            }
                        }

                        Collections.sort(ordena, new Comparator() {
                            @Override
                            public int compare(Object o1, Object o2) {
                                Renglon p1 = (Renglon) o1;
                                Renglon p2 = (Renglon) o2;
                                return new String(p1.np + p1.descripcion)
                                        .compareTo(new String(p2.np + p2.descripcion));
                            }
                        });

                        for (int c = 0; c < ordena.size() + 1; c++) {
                            Row fila = hoja.createRow(c);

                            Cell celda0 = fila.createCell(0);
                            Cell celda1 = fila.createCell(1);
                            Cell celda2 = fila.createCell(2);
                            Cell celda3 = fila.createCell(3);
                            Cell celda4 = fila.createCell(4);
                            Cell celda5 = fila.createCell(5);
                            Cell celda6 = fila.createCell(6);
                            Cell celda7 = fila.createCell(7);
                            if (c == 0) {
                                celda0.setCellValue("Pedido");
                                celda1.setCellValue("NP");
                                celda2.setCellValue("Descripcion");
                                celda3.setCellValue("Cant");
                                celda4.setCellValue("Med");
                                celda5.setCellValue("Precio");
                                celda6.setCellValue("Orden");
                                celda7.setCellValue("Partida");
                            } else {
                                Renglon r1 = (Renglon) ordena.get(c - 1);
                                celda0.setCellValue(r1.pedido);
                                celda1.setCellValue(r1.np);
                                celda2.setCellValue(r1.descripcion);
                                celda3.setCellValue(formatoPorcentaje.format(r1.cant));
                                celda4.setCellValue(r1.med);
                                celda5.setCellValue(formatoPorcentaje.format(r1.precio));
                                celda6.setCellValue("" + r1.orden);
                                celda7.setCellValue(r1.partida);
                            }
                        }

                    }
                    libro.write(archivo);
                    archivo.close();
                    Desktop.getDesktop().open(archivoXLS);
                } catch (Exception e) {
                    System.out.println(e);
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(this,
                            "No se pudo realizar el reporte si el archivo esta abierto.");
                } finally {
                    if (session != null)
                        if (session.isOpen())
                            session.close();
                }
            }
        }
    }
}

From source file:corner.service.tree.TreeService.java

License:Apache License

/**
 * /*ww  w.  ja  v  a  2 s. co m*/
 * @param page 
 * 
 * @param clazz class
 * @param depend 
 * @param depth   ?
 */
public List getDepthTree(IPage page, Class clazz, String[] depends, int depth, int left, int right) {
    DetachedCriteria criteria = DetachedCriteria.forClass(clazz);

    if (depth == 1) {
        //         select * from MP_S_ACCOUNT_ITEM_CODE where tree_depth = 1;
        criteria.add(Restrictions.eq(ITreeAdaptor.DEPTH_PRO_NAME, depth));
    } else {
        //         select * from MP_S_ACCOUNT_ITEM_CODE where tree_depth = 2 and tree_left_code > 1 and tree_right_code < 8;
        Criterion leftright = Restrictions.and(Restrictions.gt(ITreeAdaptor.LEFT_PRO_NAME, left),
                Restrictions.lt(ITreeAdaptor.RIGHT_PRO_NAME, right));
        criteria.add(Restrictions.and(Restrictions.eq(ITreeAdaptor.DEPTH_PRO_NAME, depth), leftright));
    }

    //
    if (page instanceof ITreeQueryPage) {
        ((ITreeQueryPage) page).appendCriteria(criteria, depends);
    }

    criteria.addOrder(Order.asc(ITreeAdaptor.LEFT_PRO_NAME));

    return findByCriteria(criteria);
}

From source file:cpcc.core.services.jobs.JobRepositoryImpl.java

License:Open Source License

/**
 * {@inheritDoc}/*from  ww  w  .j a v a  2  s.  c  o m*/
 */
@SuppressWarnings("unchecked")
@Override
public void removeOldJobs() {
    List<Job> oldJobs = (List<Job>) session.createCriteria(Job.class)
            .add(Restrictions.or(Restrictions.le("end", new Date(System.currentTimeMillis() - maxJobAge)),
                    Restrictions.and(Restrictions.le("end", new Date(System.currentTimeMillis() - 30000)),
                            Restrictions.in("status",
                                    new JobStatus[] { JobStatus.OK, JobStatus.FAILED, JobStatus.NO_FACTORY }))))
            .list();

    for (Job job : oldJobs) {
        logger.debug("Removing old job " + job.getId() + " " + job.getQueued() + " " + job.getQueueName() + " "
                + job.getParameters());

        session.delete(job);
    }
}

From source file:cpcc.vvrte.services.db.VvRteRepositoryImpl.java

License:Open Source License

/**
 * {@inheritDoc}/*from  w w  w. ja  v a 2  s  . com*/
 */
@Override
public VirtualVehicleStorage findStorageItemByVirtualVehicleAndName(VirtualVehicle vehicle, String name) {
    //        return (VirtualVehicleStorage) session
    //            .createQuery("from VirtualVehicleStorage where virtualVehicle.id = :id AND name = :name")
    //            .setInteger("id", vehicle.getId())
    //            .setString("name", name)
    //            .uniqueResult();

    return (VirtualVehicleStorage) session
            .createCriteria(VirtualVehicleStorage.class).add(Restrictions
                    .and(Restrictions.eq("virtualVehicle.id", vehicle.getId()), Restrictions.eq("name", name)))
            .uniqueResult();
}

From source file:cz.cuni.mff.ufal.lindat.utilities.HibernateFunctionalityManager.java

License:Open Source License

@Override
public List<UserMetadata> getUserMetadata(int epersonId) {
    return (List<UserMetadata>) hibernateUtil.findByCriterie(UserMetadata.class,
            Restrictions.and(Restrictions.eq("userRegistration.epersonId", epersonId),
                    Restrictions.isNull("licenseResourceUserAllowance")));
}

From source file:cz.cuni.mff.ufal.lindat.utilities.HibernateFunctionalityManager.java

License:Open Source License

@Override
public List<UserMetadata> getUserMetadata_License(int epersonId, int transaction_id) {
    return (List<UserMetadata>) hibernateUtil.findByCriterie(UserMetadata.class,
            Restrictions.and(Restrictions.eq("userRegistration.epersonId", epersonId),
                    Restrictions.eq("licenseResourceUserAllowance.transactionId", transaction_id)));
}

From source file:cz.jirutka.rsql.hibernate.RSQL2CriteriaConverterImplTest.java

License:Open Source License

/**
 * Finally test whole DetachedCriteria creation.
 */// w w  w . j  av a  2  s .  co m
@Test
public void testInnerConvertDetached2() {
    instance.pushCriterionBuilder(new MockCriterionBuilder());

    DetachedCriteria expResult = DetachedCriteria.forClass(Course.class, RSQL2CriteriaConverter.ROOT_ALIAS)
            .add(Restrictions.and(Restrictions.eq("foo", "flynn"),
                    Restrictions.or(Restrictions.eq("bar", 42), Restrictions.eq("baz", 42.2))));

    Expression expression = new LogicalExpression(new ComparisonExpression("foo", Comparison.EQUAL, "flynn"),
            Logical.AND, new LogicalExpression(new ComparisonExpression("bar", Comparison.EQUAL, "42"),
                    Logical.OR, new ComparisonExpression("baz", Comparison.EQUAL, "42.2")));

    DetachedCriteria result = DetachedCriteria.forClass(Course.class);
    inner.convert(expression, result);

    assertEquals(expResult.toString(), result.toString());
}

From source file:cz.jirutka.rsql.visitor.hibernate.HibernateCriterionVisitor.java

License:Apache License

@Override
public Criterion visit(AndNode node) {
    List<Node> children = node.getChildren();
    assert children.size() >= 2;
    Criterion previous = children.get(0).accept(this);
    for (int i = 1; i < children.size(); ++i) {
        previous = Restrictions.and(previous, children.get(i).accept(this));
    }/*  w w  w . j av  a 2s . co  m*/
    return previous;
}

From source file:cz.zcu.kiv.eegdatabase.data.dao.SimpleReservationDao.java

License:Apache License

public int createChecked(Reservation newInstance) throws DaoException {

    if (newInstance.getStartTime().getTime() >= newInstance.getEndTime().getTime()) {
        throw new DaoException("Time of start cannot be lower than or equal to time of end!");
    }/*from  w  w  w . j a v  a2  s .  c om*/
    Criteria overlapCriteria = getSession().createCriteria(Reservation.class);
    //start overlap
    LogicalExpression startOverlap = Restrictions.and(
            Restrictions.and(Restrictions.ge("startTime", newInstance.getStartTime()),
                    Restrictions.ge("endTime", newInstance.getEndTime())),
            Restrictions.le("startTime", newInstance.getEndTime()));
    //end overlap
    LogicalExpression endOverlap = Restrictions.and(
            Restrictions.and(Restrictions.le("startTime", newInstance.getStartTime()),
                    Restrictions.le("endTime", newInstance.getEndTime())),
            Restrictions.ge("endTime", newInstance.getStartTime()));
    //include overlap
    LogicalExpression inOverlap = Restrictions.and(Restrictions.le("startTime", newInstance.getStartTime()),
            Restrictions.ge("endTime", newInstance.getEndTime()));

    //complete overlap
    LogicalExpression completeOverlap = Restrictions.and(
            Restrictions.ge("startTime", newInstance.getStartTime()),
            Restrictions.le("endTime", newInstance.getEndTime()));

    overlapCriteria.add(Restrictions.or(Restrictions.or(inOverlap, completeOverlap),
            Restrictions.or(startOverlap, endOverlap)));

    //if some overlap was found, it is an error
    if (overlapCriteria.list().size() > 0) {
        throw new DaoException(
                "Reservation could not be created due to existing records within the time range.");
    }

    return super.create(newInstance);
}