Executing queries in Hibernate by R4R Team

HQL and native SQL queries are represented with an instance of org.hibernate.Query. This interface offers methods for parameter binding, result set handling, and for the execution of the actual query. You always obtain a Query using the current Session that is given below:

List student = session.createQuery("from Student as student where student.birthdate < ?")
    .setDate(0, date)
    .list();

List mothers = session.createQuery("select mother from Student as student join student.mother as mother where student.name = ?")
    .setString(0, name)
    .list();

List kittens = session.createQuery("from Student as student where student.mother = ?")
    .setEntity(0, pk)
    .list();

Student mother = (Student) session.createQuery("select student.mother from Student as student where student = ?")
    .setEntity(0, izi)
    .uniqueResult();]]

Query mothersWithKittens = (Student) session.createQuery("select mother from Student as mother left join fetch mother.kittens");
Set uniqueMothers = new HashSet(mothersWithKittens.list());

Entity instances retrieved by a query are in a persistent state. The uniqueResult() method offers a shortcut if you know your query will only return a single object.A query is usually executed by invoking list(). The result of the query will be loaded completely into a collection in memory. Queries that make use of eager fetching of collections usually return duplicates of the root objects, but with their collections initialized. You can filter these duplicates through a Set.
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!