MAGx2
MAGx2

Reputation: 3189

SELECT in hibernate

I don't know how to do SELECT * FROM in Hibernate without Query. I.e. I can do smt like this:

Session session = ...;
JavaBean jb = ...;
...
session.save(jb); // I'm adding jb
session.update(jb); // I'm updating jb
session.delete(jb); // I'm deleting jb

But I don't know how to select from session. The only way that I know is

list = session.createQuery("from JavaBean").list();

Upvotes: 2

Views: 7692

Answers (3)

Karthik Reddy
Karthik Reddy

Reputation: 3052

Criteria crit=session.createCriteria(Class object of a pojo class)
EX:
Criteria crit=session.createCriteria(Employee.class)
List list=crit.list();

If the above criteria is executed then it loads all employees i.e all objects of Employee pojo class from the DataBase

Internally hibernate stores each row of Employee in an object Employee class and all Employee class objects are stored in a list and finally hibernate returns that list object to our java application

While iterating the collection(List) we need to typecast each object into pojo class type.

 Iterator it=list.iterator();
while(it.hasNext())
 {
  Employee e=(Employee)it.next();
 ..............
 ..............

 }

Upvotes: 2

overmeulen
overmeulen

Reputation: 1158

To get all the instances of JavaBean, use Hibernate Criteria API :

Criteria criteria = session.createCriteria(JavaBean.class);
List javaBeans = criteria.list();

Upvotes: 3

MAGx2
MAGx2

Reputation: 3189

The answer to my question is:

List selectAll(Class clazz) {
    return session.createCriteria(clazz).list();
}

Look more at: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html

Thanks to overmeulen

Upvotes: 1

Related Questions