addheader

Tuesday, 10 July 2012

hibernate 3.0 example programs by madhav(weekend class meterial)



TUTIORALS FROM MADHAV:


     JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

    HIBERNATE-ANNOTATIONS     SPRING-IOC       SPRING –AOP-SCHEMABASED   

    SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

     SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT.... 



Hibernate 3.0 example programs by madhav:

Ex1: this is simple hibernate example program that describes keeping
Department class as persist.




Department.java

package madhav;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Department {
            @Id
            private int deptno;
            private String dname;
            private String loc;
            public int getDeptno() {
                        return deptno;
            }
            public void setDeptno(int deptno) {
                        this.deptno = deptno;
            }
            public String getDname() {
                        return dname;
            }
            public void setDname(String dname) {
                        this.dname = dname;
            }
            public String getLoc() {
                        return loc;
            }
            public void setLoc(String loc) {
                        this.loc = loc;
            }
}

@Entity:
Specifies that the class is an entity. This annotation is applied to the entity class.
Since:
Java Persistence 1.0
@Id
Specifies the primary key of an entity. The field or property to which the Id annotation is applied should be one of the following types: any Java primitive type; any primitive wrapper type; String; java.util.Date; java.sql.Date; java.math.BigDecimal; java.math.BigInteger.
Since:
Java Persistence 1.0
hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="connection.username">system</property>
        <property name="connection.password">system</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="madhav.Department" />
    </session-factory>

</hibernate-configuration>



TestCase.java

package madhav;



import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

public class TestCase {

            /**
             * @param args
             */
            public static void main(String[] args) {
                        // TODO Auto-generated method stub
                         try {
                                      // Create the SessionFactory from hibernate.cfg.xml
                                      SessionFactory  sf= new
                                      AnnotationConfiguration().configure().buildSessionFactory();
                                      Session s=sf.openSession();
                                      Transaction tx=s.beginTransaction();
                                      Department d=new Department();
                                      d.setDeptno(1);
                                      d.setDname("sales");
                                      d.setLoc("hyd");
                                      s.save(d);
                                      tx.commit();
                                     
                                      } catch (Throwable ex) {
                                      // Make sure you log the exception, as it might be swallowed
                                      System.err.println("Initial SessionFactory creation failed." + ex);
                                   
                                      }
                                      }

            }



Output in console:

Hibernate: insert into Department (dname, loc, deptno) values (?, ?, ?)



In sqlprompt:
Sql> select * from Department;

DEPTNO
DNAME
LOC
1
sales
hyd



Problem of Inheritance:

a)  Class hirerchy



Employee.java


package madhav;

import javax.persistence.Entity;
import javax.persistence.*;

@Entity
@Table(name="employeeinfo")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
    name="discriminator",
    discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue(value="e")
public class Employee {
            @Id
            private int empno;
            private String ename;
            public int getEmpno() {
                        return empno;
            }
            public void setEmpno(int empno) {
                        this.empno = empno;
            }
            public String getEname() {
                        return ename;
            }
            public void setEname(String ename) {
                        this.ename = ename;
            }
}


@Table
Specifies the primary table for the annotated entity
Ex: @Table(name="employeeinfo")

@Inheritance
Defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class hierarchy. If the Inheritance annotation is not specified or if no inheritance type is specified for an entity class hierarchy, the SINGLE_TABLE mapping strategy is used.
Ex: @Inheritance(strategy=InheritanceType.SINGLE_TABLE)





@DiscriminatorColumn
Specifies the discriminator column for the SINGLE_TABLE and JOINED Inheritance mapping strategies.
The strategy and the discriminator column are only specified in the root of an entity class hierarchy or subhierarchy in which a different inheritance strategy is applied
If the DiscriminatorColumn annotation is missing, and a discriminator column is required, the name of the discriminator column defaults to "DTYPE" and the discriminator type to DiscriminatorType.STRING.
Ex: @DiscriminatorColumn(
    name="discriminator",
    discriminatorType=DiscriminatorType.STRING
)
@ DiscriminatorValue
Specifies the value of the discriminator column for entities of the given type.
The DiscriminatorValue annotation can only be specified on a concrete entity class.
If the DiscriminatorValue annotation is not specified and a discriminator column is used, a provider-specific function will be used to generate a value representing the entity type. If the DiscriminatorType is STRING, the discriminator value default is the entity name.
The inheritance strategy and the discriminator column are only specified in the root of an entity class hierarchy or subhierarchy in which a different inheritance strategy is applied. The discriminator value, if not defaulted, should be specified for each entity class in the hierarchy
Ex:
 @DiscriminatorValue(value="e")






SalariedEmployee.java

package madhav;

import javax.persistence.DiscriminatorValue;
import javax.persistence.*;

@Entity
@Table(name="employeeinfo")
@DiscriminatorValue("se")
public class SalariedEmployee extends Employee {
            public double annualSal;

            public double getAnnualSal() {
                        return annualSal;
            }

            public void setAnnualSal(double annualSal) {
                        this.annualSal = annualSal;
            }
}



hibernate.cfg.xml


            <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="connection.username">system</property>
        <property name="connection.password">system</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="madhav.Employee" />
        <mapping class="madhav.SalariedEmployee"/>
    </session-factory>

</hibernate-configuration>





TestCase.java

                package madhav;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

public class TestCase {

                /**
                 * @param args
                 */
                public static void main(String[] args) {
                        // TODO Auto-generated method stub
                         try {
                                      // Create the SessionFactory from hibernate.cfg.xml
                                      SessionFactory  sf= new
                                      AnnotationConfiguration().configure().buildSessionFactory();
                                      Session s=sf.openSession();
                                      Transaction tx=s.beginTransaction();
                                      Employee e=new Employee();
                                      e.setEmpno(101);
                                      e.setEname("madhav");
                                     
                                      SalariedEmployee se=new SalariedEmployee();
                                      se.setAnnualSal(2000);
                                      se.setEmpno(12);
                                      se.setEname("raghu");
                                      s.save(se);
                                     
                                      s.save(e);
                                     
                                     
                                      tx.commit();
                                     
                                      } catch (Throwable ex) {
                                      // Make sure you log the exception, as it might be swallowed
                                      System.err.println("Initial SessionFactory creation failed." + ex);
                                   
                                      }
                                      }

                }




Console output:

Hibernate: insert into employeeinfo (ename, annualSal, discriminator, empno) values (?, ?, 'se', ?)
Hibernate: insert into employeeinfo (ename, discriminator, empno) values (?, 'e', ?)


Sqlprompt:

Sql> select * from employeeinfo;


DISCRIMINATOR
EMPNO
ENAME
ANNUALSAL
se
12
raghu
2000
e
101
madhav





b)      joinsubclass



Employee.java

package madhav;

import javax.persistence.Entity;
import javax.persistence.*;

@Entity
@Table(name="employee")
@Inheritance(strategy=InheritanceType.JOINED)

public class Employee {
            @Id
            private int empno;
            private String ename;
            public int getEmpno() {
                        return empno;
            }
            public void setEmpno(int empno) {
                        this.empno = empno;
            }
            public String getEname() {
                        return ename;
            }
            public void setEname(String ename) {
                        this.ename = ename;
            }
}




SalariedEmployee.java

package madhav;

import javax.persistence.DiscriminatorValue;
import javax.persistence.*;

@Entity
@Table(name="salariedemp")
@PrimaryKeyJoinColumn(name="empno")
public class SalariedEmployee extends Employee {
            public double annualSal;

            public double getAnnualSal() {
                        return annualSal;
            }

            public void setAnnualSal(double annualSal) {
                        this.annualSal = annualSal;
            }
}


@PrimaryKeyJoinColumn

Specifies a primary key column that is used as a foreign key to join to another table.
It is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity.
If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.
Ex:  @PrimaryKeyJoinColumn(name="empno")


hibernate.cfg.xml



<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="connection.username">system</property>
        <property name="connection.password">system</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="show_sql">true</property>
        <property name="hbm2ddl.auto"></property>
        <mapping class="madhav.Employee" />
        <mapping class="madhav.SalariedEmployee"/>
    </session-factory>

</hibernate-configuration>

TestCase.java

package madhav;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

public class TestCase {

            /**
             * @param args
             */
            public static void main(String[] args) {
                        // TODO Auto-generated method stub
                         try {
                                      // Create the SessionFactory from hibernate.cfg.xml
                                      SessionFactory  sf= new
                                      AnnotationConfiguration().configure().buildSessionFactory();
                                      Session s=sf.openSession();
                                      Transaction tx=s.beginTransaction();
                                      Employee e=new Employee();
                                      e.setEmpno(1);
                                      e.setEname("madhav");
                                     
                                      SalariedEmployee se=new SalariedEmployee();
                                      se.setAnnualSal(2000);
                                      se.setEmpno(107);
                                      se.setEname("ram");
           
                                      s.save(e);
                                     
                                     
                                     
                                     
                                      tx.commit();
                                     
                                      } catch (Throwable ex) {
                                      // Make sure you log the exception, as it might be swallowed
                                      System.err.println("Initial SessionFactory creation failed." + ex);
                                   
                                      }
                                      }

            }





                Console output:

Hibernate: insert into employee (ename, empno) values (?, ?)
Hibernate: insert into salariedemp (annualSal, empno) values (?, ?)


Sqlprompt:
Sql>  select * from employee;

EMPNO
ENAME
0
ram

Sql> select * from salariedemp;

ANNUALSAL
EMPNO
2000
0


Problems of relationships:

a)      one –to-one

                 


Employee.java


package madhav;

import javax.persistence.Entity;
import javax.persistence.*;

@Entity
@Table(name="employee")


public class Employee {
                         @Id
    @GeneratedValue
                         private int empno;
                         private String ename;
                          @OneToOne(mappedBy="employee", cascade=CascadeType.ALL)
                         private PersonalDetails personalDetails;
                         public PersonalDetails getPersonalDetails() {
                                    return personalDetails;
                         }
                         public void setPersonalDetails(PersonalDetails personalDetails) {
                                    this.personalDetails = personalDetails;
                         }
                         public int getEmpno() {
                                    return empno;
                         }
                         public void setEmpno(int empno) {
                                    this.empno = empno;
                         }
                         public String getEname() {
                                    return ename;
                         }
                         public void setEname(String ename) {
                                    this.ename = ename;
                         }
}

@OneToOne:

Defines a single-valued association to another entity that has one-to-one multiplicity. It is not normally necessary to specify the associated target entity explicitly since it can usually be inferred from the type of the object being referenced. If the relationship is bidirectional, the non-owning side must use the mappedBy element of the OneToOne annotation to specify the relationship field or property of the owning side.
The OneToOne annotation may be used within an embeddable class to specify a relationship from the embeddable class to an entity class. If the relationship is bidirectional and the entity containing the embeddable class is on the owning side of the relationship, the non-owning side must use the mappedBy element of the OneToOne annotation to specify the relationship field or property of the embeddable class. The dot (".") notation syntax must be used in the mappedBy element to indicate the relationship attribute within the embedded attribute. The value of each identifier used with the dot notation is the name of the respective embedded field or property.
Ex: @OneToOne(mappedBy="employee", cascade=CascadeType.ALL)



PersonalDetails.java

package madhav;

import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name="personaldetails")
public class PersonalDetails{
                         @Id
                         @GeneratedValue(generator="ram")
    @GenericGenerator(name="ram", strategy="foreign", parameters=@Parameter(name="property", value="employee"))
                         private int empno;
                         private String firstname;
                         private String lastname;
                         @OneToOne
                         @PrimaryKeyJoinColumn
                         private Employee employee;
                         public Employee getEmployee() {
                                    return employee;
                         }
                         public void setEmployee(Employee employee) {
                                    this.employee = employee;
                         }
                         public int getEmpno() {
                                    return empno;
                         }
                         public void setEmpno(int empno) {
                                    this.empno = empno;
                         }
                         public String getFirstname() {
                                    return firstname;
                         }
                         public void setFirstname(String firstname) {
                                    this.firstname = firstname;
                         }
                         public String getLastname() {
                                    return lastname;
                         }
                         public void setLastname(String lastname) {
                                    this.lastname = lastname;
                         }
}


hibernate.cfg.xml



            <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="connection.username">system</property>
        <property name="connection.password">system</property>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
    <property name="show_sql">true</property>
        <property name="hbm2ddl.auto"></property>
        <mapping class="madhav.Employee" />
        <mapping class="madhav.PersonalDetails"/>
    </session-factory>

</hibernate-configuration>



TestCase.java


package madhav;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;

public class TestCase {

            /**
             * @param args
             */
            public static void main(String[] args) {
                        // TODO Auto-generated method stub
                         try {
                                      // Create the SessionFactory from hibernate.cfg.xml
                                      SessionFactory  sf= new
                                      AnnotationConfiguration().configure().buildSessionFactory();
                                      Session s=sf.openSession();
                                      Transaction tx=s.beginTransaction();
                                     
                                      PersonalDetails pd=new PersonalDetails();
                                     
                                      pd.setFirstname("abc");
                                      pd.setLastname("rao");
                                     // pd.setEmpno(101);
                                      Employee e=new Employee();
                                     
                                      e.setEname("madhav");
                                     // e.setEmpno(101);
                                      e.setPersonalDetails(pd);
                                      pd.setEmployee(e);
                                     
                                    System.out.println("before save");
           
                                      s.save(e);
                                      System.out.println("after save");
                                      tx.commit();
                                     
                                      } catch (Throwable ex) {
                                      // Make sure you log the exception, as it might be swallowed
                                      System.err.println("Initial SessionFactory creation failed." + ex);
                                   
                                      }
                                      }

            }



Console output:



before save
Hibernate: select hibernate_sequence.nextval from dual
after save
Hibernate: insert into employee (ename, empno) values (?, ?)
Hibernate: insert into personaldetails (firstname, lastname, empno) values (?, ?, ?)

Related Topics:

  1. hibernate-basic-example(xml-based)
  2. hibernate-inheritance-tableforclass-hierarchy(xml-based)
  3. hibernate-inheritance-joinsubclass-(xml-based)
  4. hibernate-inheritance-tableforconcreteclass(xml-based)
  5. hibernate-onetoone-relation(xml-based)
  6. hibernate-onetomany-relation(xml-based)
  7. hibernate-manytomany-relation(xml-based)
  8. hibernate-basic-example(Annotation-based)
  9. hibernate-inheritance-tableforclass-hierarchy(Annotation-based)
  10. hibernate-inberitance-joinsubclass-(Annotation-based)
  11. hibernate-inheritance-tableforconcreteclass(Annotation-based)
  12. hibernate-onetoone-relation(Annotation-based)
  13. hibernate-onetomany-relation(Annotation-based)
  14. hibernate-manytomany-relation(Annotation-based)


HIBERNATE QUERY LANGUAGE:



TUTIORALS FROM MADHAV:




     JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

    HIBERNATE-ANNOTATIONS     SPRING-IOC       SPRING –AOP-SCHEMABASED   

    SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

     SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT.... 



No comments:

Post a Comment