22 November, 2013

Criteria Queries

Creating a criteria:
session.createCriteria(Cat.class)

Criterion->singular
Criteria->Plural

session.createCriteria(className).add(Restriction)
Criterion   : Restriction
            : Property
            : Expression(Deprecated)     


                  :like 
                  :or   
Restriction       :eq   
                  :between    
                  :isNull     
                  :disjunction
                  :sqlRestriction------------>specify SQL Directly



Property.forName("propName"):returns you the matching Property instance.

what is difference b/w below codes?                  
List cats = session.createCriteria(Cat.class) 
.add( Restrictions.like("name", "F%")  .list();  
and
List cats = session.createCriteria(Cat.class)    
.add( Property.forName("name").like("F%") )   .list(); 

no difference between the first two code snippets.
You should use Property.forName("propName") when you need to use that property multiple times in Criteria or Query.
It is equivalent to using direct no. (e.g. 12) or using variable assigned to the no. (e.g. int x = 12) and use the variable every time you need to use the no.

ordering 
order : asc
      : desc

List cats = session.createCriteria(Cat.class).addOrder(Order.asc("name").list()

 Association 
1) inner join:

List cats = sess.createCriteria(Cat.class).createCriteria("kittens").list();
in above ex. we are crating 2 criteria objects.

creatAlias:Join an association, assigning an alias to the joined association.
List cats = sess.createCriteria(Cat.class).creatAlias("kittens","kt")
.add(Restriction.like("kt.name","F%")).list();


21 November, 2013

Difference between Procedure and Function

Procedure Function
don't need to return value Must return value
stored in DB as compiled statement Parsed and compiled at runtime
can affect state of DB using commit Don't affect state of DB
can not be invoked from sql statement like SELECT can be invoked from sql statement
select max(sal) from Emp
used to perform business logic used to perform computation

12 November, 2013

hibernate-one-to-one mapping


      1                                 1 

Customer-------------------------------> Address

---------------------------------Address Class----------------------------

package hibernate.onetoone;

public class Address {
    private int addId;
    private String street;
    private String city;
    private String state;

    public Address(String street, String city, String state) {
        this.street = street;
        this.city = city;
        this.state = state;
    }

// getters and setters
}

-------------------Customer Class---------------------------------

package hibernate.onetoone;

public class Customer {

    private int cid;

    private String cname;

    private String email;

    private String phone;

    private String bal;

    private Address address;

  

    public Customer (String cname,String email,String phone,String bal,Address address){

        this.cname = cname;

        this.email = email;

        this.phone = phone;

        this.bal = bal;

        this.address = address;

    }
//getters and setters
}

---------------------Address.hbm.xml-------------------------------

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="hibernate.onetoone">

    <class name="Address" table="ADDRESS">

        <id name="addId">

            <generator class="increment" />

        </id>

        <property name="street" />

        <property name="city" />

        <property name="state" />

    </class>

</hibernate-mapping>

------------------------------Customer.hbm.xml--------------

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="hibernate.onetoone">

    <class name="Customer" table="CUSTOMER">

        <id name="cid">

            <generator class="increment" />

        </id>

        <property name="cname" />

        <property name="email" />

        <property name="phone" />

        <property name="bal" />

        <many-to-one name="address" class="Address" column="addId" unique="true"></many-to-one>      

    </class>

</hibernate-mapping>

  ---------------------hibernate.cfg.xml-----------------

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

        <property name="hibernate.connection.url">jdbc:oracle:thin:@Mukesh-PC:1521/XE</property>

        <property name="hibernate.connection.username">mukesh</property>

        <property name="hibernate.connection.password">mukesh</property>

        <property name="hibernate.connection.pool_size">10</property>

        <property name="hibernate.show_sql">true</property>

        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>

        <property name="hibernate.hbm2ddl.auto">update</property>

        <property name="hibernate.format_sql">true</property>

      

       

        <!-- Mapping files -->

        <mapping resource="hibernate/onetoone/Address.hbm.xml" />

        <mapping resource="hibernate/onetoone/Customer.hbm.xml" />

    </session-factory>

</hibernate-configuration>

-------------------------------------HibernateUtil.java-------------------

package hibernate.onetoone;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    public static final ThreadLocal session = new ThreadLocal();

    public static final SessionFactory sessionFactory;

    public static Session currentSession() throws HibernateException {

        Session s = (Session) session.get();

        if (s == null) {

            s = sessionFactory.openSession();

            session.set(s);

        }

        return s;

    }

    static {

        try {

            String xml = "hibernate/onetoone/hibernate.cfg.xml";

            Configuration config = new Configuration().configure(xml);

            sessionFactory = config.buildSessionFactory();

        } catch (Throwable ex) {

            System.err.println("Initial SessionFactory creation failed." + ex);

            throw new ExceptionInInitializerError(ex);

        }

    }

}

--------------------------HibernateMain.java------------------------

import org.hibernate.Session;

import org.hibernate.Transaction;

public class HibernateMain {

    public static void main(String[] args) {

        Session session = HibernateUtil.currentSession();

        Transaction tx = session.beginTransaction();

        Address add = new Address("MSR", "bangalore", "KA");

        session.save(add);

        Customer cust = new Customer("Mukesh", "a@b.com", "22222", "1000", add);

        cust.setAddress(add);

        session.save(cust);

        tx.commit();

        session.close();

    }

}