Tuesday, November 16, 2010

Hibernate-Using SQLQuery(addScalar()).

Hibernate-Using SQLQuery(addScalar()).

Use:
            To get columns from table as we desired.

Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values.

We use addScalar() to avoid the ResultSetMetadate and to order manually.

String sql=”select * from Student student;

Query query=session.createSQLQuery(sql)
                        .addScalar(“Stuname”,Hibernate.STRING)
                        .addScalar(“Tamil”,Hibernate.BIG_INTEGER)
                        .addScalar(“Science”,Hibernate.BIG_INTEGER);

It will return query.

Only these three columns (stuname,tamil,science) will be returned, although the query is using * . without addScalar(), the query is using * will return all columns.

Problem:

            We use * in select query. But we only get three columns using addScalar().

Note:
            Select * from student; it will return all columns.

Procedure:

Create Hibernate Project as HibernateNativepro.

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 NativeSelectScalar.jsp

Include following coding into the NativeSelectScalar.jsp

< %@page import="Hiber.Student"% >
< %@page import="java.util.Iterator"% >
< %@page import="java.util.List"% >
< %@page import="org.hibernate.*" % >
< %@page import="org.hibernate.cfg.*" % >
< %@page import="org.hibernate.criterion.*" % >
< html >
< head >
< title > Hibernate NativeSQL addScalar Example < /title >
< meta name="keywords" content="Hibernate NativeSQL with addScalar"/ >
< /head >
< body >
< %
try
{
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session ss=sessionFactory.openSession();

String sql="select * from Student stu";

Query query=ss.createSQLQuery(sql)
.addScalar("Stuname",Hibernate.STRING)
.addScalar("Tamil",Hibernate.BIG_INTEGER)
.addScalar("Science",Hibernate.BIG_INTEGER);

List list=query.list();
Iterator it=list.iterator();
while(it.hasNext())
{
Object[] st=(Object[])it.next();
out.println("Studentname :"+st[0]);
out.println(" < br > ");
out.println("Tamil :"+st[1]);
out.println(" < br > ");
out.println("English :"+st[2]);
out.println(" < br > ");
}

}
catch(Exception e)
{
out.println(e);
}
% >
< /body >
< /html >


Output:

No comments:

Post a Comment