Question

i need to do a query that is order by foreign key the tables:

enter image description here

this is my code:

@Transactional
    public List<Producto> busquedaPaginada(int currPosition, int pageSize, String sSearch, int iSortCol_0, String sSortDir_0){

        try {
            sessionFactory.getCurrentSession().beginTransaction();

            String columna = buscarColumna(iSortCol_0);

            @SuppressWarnings("unchecked")
            List<Producto> lista = sessionFactory.getCurrentSession().createQuery("From Producto P Where P.descripcion like '"+sSearch+"%' order by P."+columna+" "+sSortDir_0)
                .setMaxResults(pageSize).setFirstResult(currPosition).list();

            sessionFactory.getCurrentSession().getTransaction().commit();
            return lista;


        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        }finally{
            sessionFactory.getCurrentSession().close();
        }

    }

    private String buscarColumna(int iSortCol_0){
        String columna="";
        try {

            if(iSortCol_0==0)
                columna="idproducto";
            else if (iSortCol_0==1) 
                columna="anio";
            else if (iSortCol_0==2)
                columna="clave";
            else if (iSortCol_0==3)
                columna="pventa";
            else if (iSortCol_0==4)
                columna="iddepto.depto";
            else
                return "idproducto";



        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return columna;
    }

i try with this query's:

  1. Producto P Where P.descripcion like '%' order by P.iddepto.depto asc
  2. Producto P Where P.descripcion like '%' order by P.iddepto asc
Was it helpful?

Solution

You need to JOIN the tables and then you can ORDER BY any column. Alias the tables as p and d.

SELECT d.iddepto, d.ideptto, p.iproducto, p.name, p.descripcion
FROM depto d
JOIN producto p ON d.iddepto = p.iddepto
WHERE p.descripcion like '%'
ORDER BY p.iddepto ASC

WARNING: Please note that you have a SQL injection vulnerability in your code. You should sanitize your input for sSearch, columna, and sSortDir_0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top