Wednesday, November 17, 2010

Hibernate Project- SUM


Hibernate Project- SUM

Introduction:

                        We are going to understand how to use sum in Projection.

Database:




































Problem:

            To get sum of all Tamil marks.

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 nameds as ProjectionSum.jsp

            Include following coding into ProjectionSum.jsp


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

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

ProjectionList p=Projections.projectionList();
p.add(Projections.sum("tamil"));
crit.setProjection(p);

List list=crit.list();
Iterator it=list.iterator();

while(it.hasNext())
{
Object obj=(Object)it.next();
out.println(obj);
}


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

Output:

Hibernate Projection Example.


Hibernate Projection Example.

Introduction:

Problem:

            To get stuname and tamil mark from table(Student) in database(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 ProjectionExample.jsp

            Include following coding into ProjectionExample.jsp


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

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

ProjectionList p=Projections.projectionList();
p.add(Projections.property("stuname"));
p.add(Projections.property("tamil"));

crit.setProjection(p);

List list=crit.list();
Iterator it=list.iterator();
% >
< table border="3" >
< tr >
< td > Student Name < /td >
< td > Tamil Mark < /td >
< /tr >
< %
while(it.hasNext())
{
Object[] obj=(Object[])it.next();
out.println("< tr > < td > ");
out.println(obj[0]);
out.println(" < /td > < td > ");
out.println(obj[1]);
out.println(" < /td > < /tr > ");
}
% >
< /table >
< %
}
catch(Exception e)
{
out.println(e);
}
% >
< /body >
< /html >


Output

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:

Hibernate NativeSQL: Get Records From Table

 
Hibernate NativeSQL: Get Records From Table

Using SQLQueries:

·        Execution of native SQL queries is controlled via the SQLQuery interface,

·        SQLQuery  is  calling through Session.createSQLQuery().


Example for SQLQuery:


String sql=”select * from Student student”;

List list=session.createSQLQuery(sql).list();


                        (OR)

String sql=”select student.stuname,student.stuno from Student student”;

List list=session.createSQLQuery(sql).list();

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

Include following coding into the NativeSelect.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 Example < /title >
< /head >
< body >
< %
try
{
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
Session ss=sessionFactory.openSession();

String sql="select * from Student stu";

List query=ss.createSQLQuery(sql).list();

Iterator it=query.iterator();
while(it.hasNext())
{
Object[] obj=(Object[])it.next();
out.println(obj[0]);
out.println(obj[1]);
out.println(obj[2]);
out.println(obj[3]);
out.println(obj[4]);
out.println(obj[5]);
out.println(obj[6]);
out.println(obj[7]);

}

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


Output:

Hibernate Insert records into table

Problem:

To insert data into student table in navalady database.

Solution:


Procedure:


Step 1:

Create Hibernate Reverse Engineering wizard

Step 2:

Create HibernateUtil.java for Creating SessionFactory.

I have created HibernateUtil.java named as NewHibernateUtil.java.

Include following coding into NewHibernateUtil.java

package Hiber;

import java.sql.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.*;

public class NewHibernateUtil
{
public static final SessionFactory sessionFact;
static
{
try
{
sessionFact = new Configuration().configure().buildSessionFactory();
}
catch(Throwable e)
{
System.out.println("SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException
{
Session sess = (Session) session.get();
if(sess == null)
{
sess = sessionFact.openSession();
session.set(sess);
}
return sess;
}
public static void SessionClose() throws Exception
{
Session s = (Session) session.get();
if (s != null)
{
s.close();
session.set(null);
}
}
}

Step 3:
Create POJO class and mapping files

Step 4:

Create jsp file named as HCQinsert.jsp

Include following coding into the HCQinsert.jsp


< %@page import="java.util.Date"% >
< %@page import="Hiber.Student"% >
< %@page import="org.hibernate.*" % >
< %@page import="org.hibernate.cfg.*" % >
< %@page import="Hiber.NewHibernateUtil" % >
< html >
< head >
< title > Hibernate Native SQL-Insert into table < /title >
< /head >
< body >
< %! Session sz; % >
< %
try
{
sz=NewHibernateUtil.currentSession();
Transaction tz=sz.beginTransaction();

Student st=new Student();
st.setStuname("Nithya");
st.setStuno(1003);
st.setTamil(69);
st.setEnglish(64);
st.setMaths(90);
st.setScience(79);
st.setSocialscience(87);
Date d=new Date("1999/06/25");
st.setJoindate(d);
sz.save(st);

out.println("Successfully Inserted into the Student table in Navalady Datebase");
tz.commit();

}
catch(Exception e)
{
sz.close();

out.println("Error Occur");
}

% >
< /body >
< /html >

output



Now we have to check using mysql database using following query.

mysql > select * from student;

Monday, November 15, 2010

Hibernate Insert records into table



Problem:
               To insert data into student table in navalady database.

Solution:

Procedure:

Step 1:
            Create Hibernate Reverse Engineering wizard

Step 2:
            Create HibernateUtil.java for Creating SessionFactory.

            I have created HibernateUtil.java named as NewHibernateUtil.java.

            Include following coding into NewHibernateUtil.java

package Hiber;

import java.sql.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.*;

public class NewHibernateUtil
{
  public static final SessionFactory sessionFact;
  static
  {
    try
    {
      sessionFact = new Configuration().configure().buildSessionFactory();
    }
    catch(Throwable e)
    {
      System.out.println("SessionFactory creation failed." + e);
      throw new ExceptionInInitializerError(e);
    }
  }
  public static final ThreadLocal session = new ThreadLocal();

  public static Session currentSession() throws HibernateException
  {
    Session sess = (Session) session.get();
    if(sess == null)
    {
      sess = sessionFact.openSession();
      session.set(sess);
    }
    return sess;
  }
  public static void SessionClose() throws Exception
  {
    Session s = (Session) session.get();
    if (s != null)
    {
        s.close();
        session.set(null);
      }
  }
}

Step 3:
            Create POJO class and mapping files

Step 4:

            Create jsp file named as HCQinsert.jsp

Include following coding into the HCQinsert.jsp


&lt %@page import="java.util.Date"% &gt
&lt %@page import="Hiber.Student"% &gt
&lt %@page import="org.hibernate.*" % &gt
&lt %@page import="org.hibernate.cfg.*" % &gt
&lt %@page import="Hiber.NewHibernateUtil" % &gt
&lt html &gt
    &lt head &gt
        &lt title &gt Hibernate Native SQL-Insert into table &lt /title &gt
    &lt /head &gt
    &lt body &gt
        &lt %! Session sz; % &gt
        &lt %
            try
            {
               sz=NewHibernateUtil.currentSession();
               Transaction tz=sz.beginTransaction();
              
               Student st=new Student();
               st.setStuname("Nithya");
               st.setStuno(1003);
               st.setTamil(69);
               st.setEnglish(64);
               st.setMaths(90);
               st.setScience(79);
               st.setSocialscience(87);
               Date d=new Date("1999/06/25");
               st.setJoindate(d);
               sz.save(st);

               out.println("Successfully Inserted into the Student table in Navalady Datebase");
               tz.commit();
              
            }
            catch(Exception e)
            {
                sz.close();
               
                out.println("Error Occur");
            }
          
         % &gt
    &lt /body &gt
&lt /html &gt

Hibernate Criteria Query-OR Clause

Hibernate Criteria Query – Using OR clause.

Aim:
            To check more than one condition using OR clause.

Example:

Problem:

            To get student name who get tamil mark between greater than 50 or less than70.

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

Include following coding into the OrExample.jsp


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

Criteria c=s.createCriteria(Student.class);
c.add(Expression.or(Expression.gt("tamil",new Integer(50)), Expression.lt("tamil", new Integer(70))));
List list=c.list();
Iterator it=list.iterator();
while(it.hasNext())
{
Student s1=(Student)it.next();
out.println(s1.getStuname());
}
}
catch(Exception e)
{

}
% >
< /body >
< /html >

Output










To check using mysql database.

Using following mysql query

mysql > select stuname from student where tamil >50 or tamil <70;