Thursday, November 11, 2010

Hibernate Criteria Query

Hibernate Criteria Query


·        Criteria interface allows us to create and execute object-oriented queries.
·        The interface org.hibernate.Criteria is used to create the criterion for the search.
·        Hibernate Criteria Query is better than Hibernate Query Language (HQL).
·        Used to get all records from table without query.



Problem:

              We are going to select all records from table student in navalady database.

Solution:

Step 1:
            Create Hibernate Reverse Engineering wizard

Step 2:
            Create HibernateUtil.java

Step 3:
            Create POJO class and mapping files
Step 4:

            Create jsp file named as CriteriaExample.jsp

Include following coding into the CriteriaExample.jsp



< %@page contentType="text/html" pageEncoding="UTF-8"% >

< %@page import="Hiber.Student"% >
< %@page import="org.hibernate.*" % >
< %@page import="org.hibernate.cfg.Configuration" % >
< %@page import="java.util.*" % >
< html >
< head >
< title > Criteria Example < /title >
< /head >
< body >
< h1 > Navaladiyan College < /h1 >
< %
try
{
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session s=sessionFactory.openSession();

Criteria crit=s.createCriteria(Student.class);

List list=crit.list();

Iterator it=list.iterator();
% >
< table border="1" >
< caption > Student Records < /caption >
< tr >
< td > Student Name < /td >
< td > Student No < /td >
< td > Tamil < /td >
< td > English < /td >
< td > Mathematics < /td >
< td > Science < /td >
< td > Social Science < /td >
< /tr >
< %
while(it.hasNext())
{
Student stu=(Student)it.next();
out.println(" < tr > < td > "+stu.getStuname()+" < /td > ");

out.println(" < td > "+stu.getStuno()+" < /td > ");

out.println(" < td > "+stu.getTamil()+" < /td > ");

out.println(" < td > "+stu.getEnglish()+" < /td > ");

out.println(" < td > "+stu.getMaths()+" < /td > ");

out.println(" < td > "+stu.getScience()+" < /td > ");

out.println(" < td > "+stu.getSocialscience()+" < /td > ");

}
% >
< /table >
< %

}
catch(Exception e)
{

}
% >
< /body >
< /html >

Step 5:

            Run the program CriteriaExample.jsp
 
Step 6:

            Get the Output




If you want to check the result is right or wrong.

Goto the mysql

Give the following query

Mysql > select * from student;

Thank you

S.Sureshkumar, M.Sc, M.Phil.

No comments:

Post a Comment