May 12 2015

Hibernate createquery example

Hibernate createquery example

Session createQuery method creates a new instance of Query for the given HQL query string.

Query createQuery(String queryString) throws HibernateException

Query.executeUpdate()

Runs the query and returns the number of records that has been inserted, updated and deleted.

Query query = session
 .createQuery("delete from Student where course='MS'");

 int records = query.executeUpdate();

Query.list()

Runs the query and returns a list of objects

Query query = session
 .createQuery("from Student where studentName='Mark'");

 List<Student> students = query.list();

 Binding parameters

Hibernate supports two different types of parameter binding to the query

Positional parameters – It is indicated by ? In the query string

Query query = session.createQuery("delete from Student where course=?");

int deletedRecords = query.setParameter(0, "MBA").executeUpdate();

Named parametersIt is indicated by colon followed by parameter

Query query = session
 .createQuery("Update Student set course=:course where studentId=:studentId");

 int updatedRecords = query.setParameter("course", "MBA")
 .setParameter("studentId", 101).executeUpdate();

Binding arbitrary arguments

The Query interface provides data type specific methods to bind arguments to query parameters.

Example:  setString, setInteger

Query query = session
 .createQuery("Update Student set course=:course where studentId=:studentId");

 int updatedRecords = query.setInteger("studentId", 102)
 .setString("course", "MS").executeUpdate();


Copyright © 2014. All rights reserved.

Posted May 12, 2015 by answersz in category Hibernate

Leave a Comment

Your email address will not be published. Required fields are marked *

*