0

In Simple JDBC (with no Hibernate) we can do batch select by changing only place holder, like this

PreparedStatement stmt = conn.prepareStatement(
    "select id, name from users where id = ?");
for ( int i=0; i < 10; i++ ) {
  stmt.setInt(i);  // or whatever values you are trying to query by
  // execute statement and get result
}

How we can do it in Hibernate?

2 Answers 2

2

Hope this helps you out,

 String hql = "from Users s where s.id= :userId";

 for(int i=0; i< 10;i++){
 List result = session.createQuery(hql)
    .setParameter("userId", i)
    .list();
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is the most common and user friendly way. It use colon followed by a parameter name (:example) to define a named parameter

Example 1: Using setParameter() method

String hql = "from Student s where s.registerNumner = :registerNumner";
List result = session.createQuery(hql).setParameter("registerNumner", "12345").list();

The setParameter() method is smart enough to discover the parameter data type of bind variable.

Example 2: Using setString() method

You can use setString to tell Hibernate this parameter date type is String.

String hql = "from Student s where s.registerNumber = :registerNumber";
List result = session.createQuery(hql).setString("registerNumber", "12345").list();

Example 3: Using setProperties() method

This feature is great ! You can pass an object into the parameter binding. Hibernate will automatic check the object’s properties and match with the colon parameter.

Student student = new Student();
Student.setRegisterNumber("12345");

String hql = "from Strudent s where s.registerNumber = :registerNumber";
List result = session.createQuery(hql).setProperties(student).list();

Example 4:

You can use positional parameters also.

String hql = "from Student s where s.registerNumber = ? and s.studentName = ?";
List result = session.createQuery(hql).setString(0, "12345").setParameter(1, "Harshad").list();

But it’s vulnerable to easy breakage because every change of the position(i.e. index) of the bind parameters requires a change to the parameter binding code

Batch select:

You can use following way for batch select

String hql = "from Users s where s.id= :userId";
List finalResult = new ArrayList();
for(int i=0; i< 10;i++){
   List result = session.createQuery(hql).setParameter("userId", i).list();
   finalResult.addCollection(result );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.