Thursday, January 30, 2014

Hibernate Tutorials :

In the next few posts i will try to explain what hibernate is and how to program using hibernate framework.

What is hibernate :
Q: If you were to develop a java based application using some traditional DB as back-end, how do we provide the mapping between  tables of DB and java which understands only objects?
Ans : Hibernate is the open source framework which  provides Object/Relation mapping. It helps to persist the data from tables in the form of objects. It also provides querying facility by providing mapping between java data types and SQL types.
-> Hibernate provides smart querying of data and minimizes access to DB by fetching the data in an intelligent way.
-> Hibernate uses XML files to map between java objects and tables.

Demo1 : Insert a record into the table using hibernate
http://www.mkyong.com/hibernate/maven-3-hibernate-3-6-oracle-11g-example-xml-mapping/

Take aways :

1. Create a table and create a corresponding java file for the same.
2. Create a XML file and define the mapping between java object and table.
     
DBUser.hbm.xml
  <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.mkyong.user.DBUser" table="DBUSER">
        <id name="userId" type="int">
            <column name="USER_ID" precision="5" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="username" type="string">
            <column name="USERNAME" length="20" not-null="true" />
        </property>
        <property name="createdBy" type="string">
            <column name="CREATED_BY" length="20" not-null="true" />
        </property>
        <property name="createdDate" type="date">
            <column name="CREATED_DATE" length="7" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

3. Specify this XML file in hibernate mapping file.

<?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">
<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:MKYONG</property>
  <property name="hibernate.connection.username">mkyong</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">MKYONG</property>
  <property name="show_sql">true</property>
  <mapping resource="com/mkyong/user/DBUser.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
4. Create a file HibernateUtil.java which will take care of session management.

package com.mkyong.util;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
 
	private static final SessionFactory sessionFactory = buildSessionFactory();
 
	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
 
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
 
	public static void shutdown() {
		// Close caches and connection pools
		getSessionFactory().close();
	}
 
}
5. create the main program App.java
package com.mkyong;
 
import java.util.Date;
import org.hibernate.Session;
import com.mkyong.util.HibernateUtil;
import com.mkyong.user.DBUser;
 
public class App {
	public static void main(String[] args) {
		System.out.println("Maven + Hibernate + Oracle");
		Session session = HibernateUtil.getSessionFactory().openSession();
 
		session.beginTransaction();
		DBUser user = new DBUser();
 
		user.setUserId(100);
		user.setUsername("superman");
		user.setCreatedBy("system");
		user.setCreatedDate(new Date());
 
		session.save(user);
		session.getTransaction().commit();
	}
}
6. hibernate.dialect. This property makes Hibernate generate the appropriate SQL for the chosen database. 



Demo2 : Same example as Demo1 using Annotations.

http://www.mkyong.com/hibernate/maven-3-hibernate-3-6-oracle-11g-example-annotation/

Takeaways:

The @Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.
The @Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If @Table annotation is not specified then Hibernate will by default use the class name as the table name.
The @Id annotation is used to specify the identifier property of the entity bean. The placement of the@Id annotation determines the default access strategy that Hibernate will use for the mapping. If the@Id annotation is placed over the field, then filed access will be used. Instead if it placed over the getter method of that field, then property access will be used. Here we use property access.
The @GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.
The @Column annotation is used to specify the details of the column to which a field or property will be mapped. Here the courseId property is mapped to COURSE_ID column in the COURSES table. If the @Column annotation is not specified by default the property name will be used as the column name.

Q: Now the big question is should you use annotations? 
Ans: If your answer is yes to the following questions then you can use annotations in your project.
  • Do you have the flexibility to use Java 5 Environment?
  • Do you have the knowledge of which production database you are going to use? If yes, you can use annotations, this brings in strong coupling. Inorder to support multiple databases, it is better to have the mapping information in a seperate xml file rather than using annotations. You can easily have multiple xml files each specific for a particular database rather than having a different sets of source codes.
Instead than keeping the mapping informations in a seperate file, using annotations you can always keep them along with the source code, in this way the soure code and mapping information will always be in sync.
Hibernate Association :
1. One-to-One Example(Using XML) 
Demo : 






Friday, November 4, 2011

Finally decided to blog!!Here comes my first post :)

Finally made up my mind to blog. Having realized tat i shud put my thoughts some where, found blogging to be a good option. Now , having decided dat , i started writing my first post, without any idea of what to write and how to write.
What is this blog about??
-> I'm a guy who get fascinated by intelligent algorithms and the wonders one can do with computers.This will be majorly a technical blog covering my experiences in various interviews regarding algorithms and datastructures, the questions which interest me, questions which i came across various sources.
->In this blog i will also put my personal thoughts about various things.

Hope people will find this blog to be useful and to an extent entertaining :).
Hurray!!! i completed my first step in blogging. As one of my frnds said , creating a blog is step 0.