Example usage for org.hibernate FetchMode JOIN

List of usage examples for org.hibernate FetchMode JOIN

Introduction

In this page you can find the example usage for org.hibernate FetchMode JOIN.

Prototype

FetchMode JOIN

To view the source code for org.hibernate FetchMode JOIN.

Click Source Link

Document

Fetch using an outer join.

Usage

From source file:com.valco.dao.NotasVentaDAO.java

public NotasDeVenta getNotaDeVentaXFolio(int folio) throws Exception {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;//from  w ww . ja va2  s . c  o  m
    NotasDeVenta nota = new NotasDeVenta();
    try {
        tx = session.beginTransaction();
        Criteria q = session.createCriteria(NotasDeVenta.class).setFetchMode("repartidores", FetchMode.JOIN)
                .setFetchMode("productosInventarios", FetchMode.JOIN).add(Restrictions.eq("folio", folio));
        nota = (NotasDeVenta) q.uniqueResult();
        return nota;

    } catch (HibernateException he) {
        throw new Exception("Ocurri un error al consultar los clientes.");

    } finally {
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (HibernateException he) {
            throw new Exception("Ocurri un error al consultar los clientes.");
        }
    }
}

From source file:com.valco.dao.NotasVentaDAO.java

public List<NotasDeVenta> getNotasDeVentaXCliente(Clientes cliente) throws Exception {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;/*from w w w  .  j  a  v  a 2 s .  co  m*/
    List<NotasDeVenta> notas = new ArrayList<NotasDeVenta>();
    try {
        tx = session.beginTransaction();
        Criteria q = session.createCriteria(NotasDeVenta.class).setFetchMode("cuentasXCobrars", FetchMode.JOIN)
                .add(Restrictions.eq("clientes", cliente));
        notas = (List<NotasDeVenta>) q.list();
        for (NotasDeVenta nota : notas) {
            for (CuentasXCobrar cuenta : nota.getCuentasXCobrars()) {
                Hibernate.initialize(cuenta);

            }
            Hibernate.initialize(nota.getProductosInventarios());
        }
        return notas;

    } catch (HibernateException he) {
        throw new Exception("Ocurri un error al consultar los clientes.");

    } finally {
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (HibernateException he) {
            throw new Exception("Ocurri un error al consultar los clientes.");
        }
    }
}

From source file:com.valco.dao.ProductoDAO.java

public List<Productos> getProductos() throws Exception {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = null;/*www .j a  v  a 2s .c o m*/
    List<Productos> productos = new ArrayList<Productos>();
    try {
        tx = session.beginTransaction();
        Criteria q = session.createCriteria(Productos.class).setFetchMode("tipoProducto", FetchMode.JOIN);
        q.setFetchMode("unidadesDeMedida", FetchMode.JOIN);
        productos = (List<Productos>) q.list();
        return productos;

    } catch (HibernateException he) {
        throw new Exception("Ocurri un error al consultar los producto.");

    } finally {
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (HibernateException he) {
            throw new Exception("Ocurri un error al consultar los producto.");
        }
    }
}

From source file:com.valco.dao.UsuariosDAO.java

public List<Usuarios> getUsuarios() throws Exception {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = null;//from   w w  w . j a  v a 2  s  .co m
    List<Usuarios> usuarios = new ArrayList<Usuarios>();
    try {
        tx = session.beginTransaction();
        Criteria q = session.createCriteria(Usuarios.class).setFetchMode("ubicaciones", FetchMode.JOIN);

        usuarios = (List<Usuarios>) q.list();
        return usuarios;

    } catch (HibernateException he) {
        throw new Exception("Ocurri un error al consultar el usuario.");

    } finally {
        try {
            if (session.isOpen()) {
                session.close();
            }
        } catch (HibernateException he) {
            throw new Exception("Ocurri un error al consultar el usuario.");
        }
    }
}

From source file:com.vg.nplusone.App.java

/**
 * try to use FetchMode = JOIN with criteria
 * it doesn't work as expected//  w ww  .j  a v a2  s . c o m
 */
private static void readWithJoinCriteria() {
    Session session = NPlusOneHibernateUtil.getSessionFactory().openSession();

    session.beginTransaction();
    User u = (User) session.createCriteria(User.class).setFetchMode("permissions", FetchMode.JOIN)
            .add(Restrictions.idEq(1)).uniqueResult();
    System.out.println(u.getName());
    for (Permision p : u.getPermisions()) {
        System.out.println(p.getRole());
    }

    session.getTransaction().commit();
}

From source file:com.wavemaker.runtime.data.task.AbstractReadTask.java

License:Open Source License

protected void fetch(Criteria criteria, String propertyName) {
    criteria.setFetchMode(propertyName, FetchMode.JOIN);
}

From source file:com.yahoo.elide.datastores.hibernate3.HibernateTransaction.java

License:Apache License

private <T> void joinCriteria(Criteria criteria, final Class<T> loadClass, RequestScope scope) {
    EntityDictionary dictionary = scope.getDictionary();
    String type = dictionary.getJsonAliasFor(loadClass);
    Set<String> fields = Objects.firstNonNull(scope.getSparseFields().get(type),
            Collections.<String>emptySet());
    for (String field : fields) {
        try {//from   w w w. j a v a2  s. c  o  m
            checkFieldReadPermission(loadClass, field, scope);
            criteria.setFetchMode(field, FetchMode.JOIN);
        } catch (ForbiddenAccessException e) {
            // continue
        }
    }

    for (String include : getIncludeList(scope)) {
        criteria.setFetchMode(include, FetchMode.JOIN);
    }
}

From source file:cz.muni.fi.pa036.betting.service.EventServiceImpl.java

@Override
public List<Event> findAllPaged(int page, int limit, List<UserFavoriteSport> favoriteSports) {
    Criteria criteria = ((EventDAOImpl) dao).getSessionFactory().getCurrentSession().createCriteria(Event.class)
            .setFetchMode("league", FetchMode.JOIN).setFetchMode("league.sport", FetchMode.JOIN)
            .createAlias("league", "l").createAlias("l.sport", "s");

    for (UserFavoriteSport favoriteSport : favoriteSports) {
        if (favoriteSport.getId().getSportid() > 0) {
            criteria.addOrder(new MyOrder("s.id", false, favoriteSport.getId().getSportid()));
        }/*  w  w  w . jav a 2s  .c o  m*/
    }

    criteria.addOrder(Order.asc("date")).addOrder(Order.asc("id"))
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).setFirstResult((page - 1) * limit)
            .setMaxResults(limit);

    return criteria.list();
}

From source file:dao.daoVenda.java

public List<Venda> getVenda() {
    Session sessao = null;/*from  w w  w. ja v  a2  s  .co  m*/
    String nome = "";
    try {
        sessao = dao.HibernateUtil.getSessionFactory().openSession();
        sessao.beginTransaction();

        //HQL
        //List<Cliente> res = sessao.createQuery("from Cliente cli JOIN FETCH cli.cidade ").list();
        // CRITERIA
        Criteria cons = sessao.createCriteria(Venda.class);
        cons.setFetchMode("produto", FetchMode.JOIN);
        cons.setFetchMode("vendedor", FetchMode.JOIN);

        //cons.add(Restrictions.like("idVenda", nome + "%"));

        cons.addOrder(Order.asc("idVenda"));

        List<Venda> res;
        res = cons.list();

        sessao.getTransaction().commit();
        sessao.close();
        return res;
    } catch (HibernateException he) {
        if (sessao != null) {
            sessao.getTransaction().rollback();
            sessao.close();
        }
        System.out.println("Erro ao listar as VENDAS: " + he.getMessage());
        return null;
    }
}

From source file:de.appsolve.padelcampus.db.dao.generic.BaseEntityDAO.java

@SuppressWarnings("unchecked")
@Override/* w  w w. j a  v  a2  s  .com*/
public Page<T> findAllFetchEagerly(Pageable pageable, Set<Criterion> criterions, String... associations) {
    //http://stackoverflow.com/questions/2183617/criteria-api-returns-a-too-small-resultset

    //get the ids of every object that matches the pageable conditions
    //we cannot get the objects directly because we use FetchMode.JOIN which returns the scalar product of all rows in all affected tables
    //and CriteriaSpecification.DISTINCT_ROOT_ENTITY does not work on SQL Level but on in Java after the result is returned from SQL
    Criteria criteria = getPageableCriteria(pageable);
    if (criterions != null) {
        for (Criterion c : criterions) {
            criteria.add(c);
        }
    }
    criteria.setProjection(Projections.distinct(Projections.property("id")));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List<Long> list = criteria.list();

    //once we have the required ids we query for the complete objects
    Criteria objectCriteria = getCriteria();
    for (String association : associations) {
        objectCriteria.setFetchMode(association, FetchMode.JOIN);
    }
    if (!list.isEmpty()) {
        objectCriteria.add(Restrictions.in("id", list));
    }
    objectCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    addOrderBy(objectCriteria, pageable);
    List<T> objects = objectCriteria.list();
    sort(objects);

    //we also need the total number of rows
    Criteria rowCountCritieria = getCriteria();
    if (criterions != null) {
        for (Criterion c : criterions) {
            rowCountCritieria.add(c);
        }
    }
    rowCountCritieria.setProjection(Projections.rowCount());
    Long resultCount = (Long) rowCountCritieria.uniqueResult();
    if (resultCount == null) {
        resultCount = objects.size() + 0L;
    }
    Collections.sort(objects);
    PageImpl<T> page = new PageImpl<>(new ArrayList<>(objects), pageable, resultCount);
    return page;
}