Problem when creating query using hibernate

1

I am making the following query:

    @Override
    public List<Estudiante> buscarEstudiantes() {   
        Session session = getSession();
        Query query = session.createSQLQuery("from Estudiante");        
        return query.list();
    }

And return the following error:

  

HTTP Status 500 - Request processing failed; nested exception is   org.hibernate.exception.SQLGrammarException: could not extract   ResultSet

The only way that works the query is if I use the names of the columns of the table but if I try to use the names of class properties gives me error.

See if it works:

    @Override
    public List<Estudiante> buscarEstudiantesSinCurso() {
        Session session = getSession();
        Query query = session.createSQLQuery("SELECT E.Est_Primer_Nombre FROM Estudiante E");
        return query.list();
    }

Student class:

@Entity
@Table(name="estudiante") 
public class Estudiante {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "est_id")
    private int id;

    @Column(name = "est_rut")
    private String rut;

    @NotNull
    @Size(min=3, max=50)
    @Column(name = "est_primer_nombre", nullable = false)
    private String primerNombre;

    @Size(min=3, max=50)
    @Column(name = "est_segundo_nombre", nullable = true)
    private String segundoNombre;

    @NotNull
    @Size(min=3, max=50)
    @Column(name = "est_primer_apellido", nullable = false)
    private String primerApellido;

    @NotNull
    @Size(min=3, max=50)
    @Column(name = "est_segundo_apellido", nullable = false)
    private String segundoApellido;


    @NotNull
    @DateTimeFormat(pattern="dd/MM/yyyy") 
    @Column(name = "est_fecha_nacimiento", nullable = false)
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
    private LocalDate fechaNacimiento;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "estudiantes")
    private Set<Curso> cursos = new HashSet<Curso>(0);

    // aquí, getters y setters
}

I found several questions similar to mine but no solution worked for me.

How can I do to use the names of the properties of the class and do not have to put the name of the column.

I am using hibernate 4.3.6.

    
asked by rod256 01.04.2016 в 18:43
source

2 answers

1

You're using a createSQLQuery that's why it sends you an error, since you create a native SQL.

Try:

    Session session = getSession();
    Query query = session.createQuery("from Estudiante");        
    return query.list();

instead to create a query with HQL

Let's say that createSQLQuery is for native SQL queries ie

Select * From Tabla

Y createQuery is for Hibernate Query Language (HQL) ie

From Tabla
    
answered by 01.04.2016 / 18:45
source
2

On a single line, using createCriteria :

public List<Estudiante> list() {
    return getSession().createCriteria(Estudiante.class).list();
}
    
answered by 01.04.2016 в 19:49