<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Free practice test , mock test, driving test, interview questions &#187; Hibernate Tutorial</title>
	<atom:link href="http://www.skill-guru.com/blog/tag/hibernate-tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.skill-guru.com/blog</link>
	<description>Find free mock and practice test, create and sell tests</description>
	<lastBuildDate>Mon, 16 Jan 2012 16:53:10 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Hibernate Persistence Tutorial: Use Hibernate in your java applications to access database</title>
		<link>http://www.skill-guru.com/blog/2009/08/17/hibernate-advanced-tutorial-use-hibernate-in-your-java-applications-to-access-database/</link>
		<comments>http://www.skill-guru.com/blog/2009/08/17/hibernate-advanced-tutorial-use-hibernate-in-your-java-applications-to-access-database/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 19:39:22 +0000</pubDate>
		<dc:creator>smitha</dc:creator>
				<category><![CDATA[Programming / tutorials]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[Hibernate Tutorial]]></category>

		<guid isPermaLink="false">http://www.skill-guru.com/blog/?p=374</guid>
		<description><![CDATA[This is third hibernate tutorial for advanced users .We will talk about hibernate persistence  and how you will connect with hibernate to the database. The database we would be using is mysql.
Our last two posts had covered hibernate setup , hibernate configuration and how using annotation with hibernate.
First Hibernate Tutorial 
Hibernate Using Annotations
 
Step 1:  Create [...]]]></description>
			<content:encoded><![CDATA[<p>This is third hibernate tutorial for advanced users .We will talk about hibernate persistence  and how you will connect with hibernate to the database. The database we would be using is mysql.</p>
<p>Our last two posts had covered hibernate setup , hibernate configuration and how using annotation with hibernate.</p>
<p><a href="http://www.skill-guru.com/blog/2009/08/05/first-hibernate-tutorial-%E2%80%93get-hands-on-experience">First Hibernate Tutorial </a></p>
<p><a href="http://www.skill-guru.com/blog/2009/08/06/hibernate-tutorial-continued-using-annotations/">Hibernate Using Annotations</a><br />
<strong> </strong></p>
<p><strong>Step 1:  Create java project in eclipse</strong></p>
<p><strong>Step2: add the required libraries. </strong></p>
<p><span id="more-374"></span></p>
<p><strong> </strong>These steps are well explained with screenshots in :</p>
<p><strong>The required jars used in my projects are:</strong></p>
<p><strong>mysql-connector.jar<br />
ejb3-persistence.jar, antlr-2.7.6.jar<br />
asm.jar<br />
asm-attrs.jar<br />
commons-collections-2.1.1.jar<br />
commons-logging-1.0.4.jar<br />
concurrent-1.3.2.jar<br />
connector.jar<br />
dom4j-1.6.1.jar<br />
ehcache-1.2.3.jar<br />
hibernate3.jar<br />
hibernate-annotations.jar<br />
hibernate-entitymanager.jar<br />
hibernate-tools.jar<br />
jaas.jar<br />
jacc-1_0-fr.jar<br />
javassist.jar<br />
jaxen-1.1-beta-7.jar<br />
jboss-cache.jar<br />
jboss-common.jar<br />
jboss-jmx.jar<br />
jboss-system.jar<br />
jdbc2_0-stdext.jar<br />
jgroups-2.2.8.jar<br />
jta.jar<br />
log4j-1.2.11.jar<br />
oscache-2.1.jar<br />
proxool-0.8.3.jar<br />
swarmcache-1.0rc2.jar<br />
syndiag2.jar<br />
xerces-2.6.2.jar<br />
xml-apis.jar</strong></p>
<p><strong>Step 3:</strong></p>
<p>The Directory structure of the application:</p>
<p>I created a following structure:</p>
<p><strong>Com.myapp.eo</strong> this package will contain all the Entity Classes.</p>
<p><strong>Com.myapp.vo</strong> this package will contain all the beans for Entity Classes.</p>
<p><strong>Com.myapp.accessor</strong> this package contains interfaces common to both eo and vo packages</p>
<p><strong>Com.myapp.hibernate </strong>for hibernate utility classes</p>
<p><strong>Com.myapp.services</strong> for the beans which will query database</p>
<p><strong>Com.myapp.client </strong>the client programs which will call service functions</p>
<p><strong>Com.myapp.exception </strong><strong>will contain all the possible exceptions thrown by our application.</strong></p>
<p><strong> </strong></p>
<p>Now create database Entity class.</p>
<p>DB Setup:</p>
<address><strong>Create database myapp_db;</strong></address>
<address><strong>Connect myapp_db;</strong></address>
<p>Create a table with following fields:</p>
<address><strong>Create table users values(user_id int(11) auto_increment,</strong></address>
<address><strong>Username varchar(100),</strong></address>
<address><strong>Password varchar(20)),</strong></address>
<address><strong>Status tinyint(1) default 0,</strong></address>
<address><strong>Primary key user_id);</strong></address>
<p>Now for every db table we’ll have 3 files for each:</p>
<p>One in accessor class which is a common interface to both com.myapp.eo and com.myapp.vo classes. The vo class is a simple java bean. We use this bean in eo class in setter and getter methods.</p>
<p>Interface: User.java. Add following interface to com.myapp.accessor package.</p>
<blockquote><p><strong>package</strong> com.myapp.accessor;</p>
<p><strong>public</strong> <strong>interface</strong> User {</p>
<p><strong>public</strong> Integer getUserId();</p>
<p><strong>public</strong> <strong>void</strong> setUserId(Integer userId);</p>
<p><strong>public</strong> String getUserName();</p>
<p><strong>public</strong> <strong>void</strong> setUserName(String userName);</p>
<p><strong>public</strong> String getPassword();</p>
<p><strong>public</strong> <strong>void</strong> setPassword(String password);</p>
<p><strong>public</strong> Byte getState();</p>
<p><strong>public</strong> <strong>void</strong> setState(Byte state);</p>
<p>}</p></blockquote>
<p>File:UserVO.java. Add this to com.myapp.vo package</p>
<blockquote>
<p style="text-align: center;">package com.myapp.vo;</p>
<p>import com. myapp.accessor.User;</p>
<p>public class UserVO implements User{</p>
<p>Integer userId;</p>
<p>String userName;</p>
<p>String password;</p>
<p>Byte state;</p>
<p>public Integer getUserId() {</p>
<p>return userId;</p>
<p>}</p>
<p>public void setUserId(Integer userId) {</p>
<p>this.userId = userId;</p>
<p>}</p>
<p>public String getUserName() {</p>
<p>return userName;</p>
<p>}</p>
<p>public void setUserName(String userName) {</p>
<p>this.userName = userName;</p>
<p>}</p>
<p>public String getPassword() {</p>
<p>return password;</p>
<p>}</p>
<p>public void setPassword(String password) {</p>
<p>this.password = password;</p>
<p>}</p>
<p>public Byte getState() {</p>
<p>return state;</p>
<p>}</p>
<p>public void setState(Byte state) {</p>
<p>this.state = state;</p>
<p>}</p>
<p>}</p></blockquote>
<p>The UserEO class: Add this to</p>
<blockquote><p><strong>package com.myapp.eo;</strong></p>
<p><strong> </strong></p>
<p>import javax.persistence.Column;</p>
<p>import javax.persistence.Entity;</p>
<p>import javax.persistence.GeneratedValue;</p>
<p>import javax.persistence.GenerationType;</p>
<p>import javax.persistence.Id;</p>
<p>import javax.persistence.Table;</p>
<p>import javax.persistence.Transient;</p>
<p>import com.jda.server.accessor.User;</p>
<p>import com.jda.server.vo.UserVO;</p>
<p>@Entity</p>
<p>@Table(name=&#8221;users&#8221;)</p>
<p>public class UserEO implements User{</p>
<p>User user;</p>
<p>@Transient</p>
<p>public User getUser() {</p>
<p>return user;</p>
<p>}</p>
<p>public void setUser(User user) {</p>
<p>this.user = user;</p>
<p>}</p>
<p>public UserEO(){</p>
<p>user = new UserVO();</p>
<p>}</p>
<p>public UserEO(User user){</p>
<p>this.user = user;</p>
<p>}</p>
<p>@Id</p>
<p>@GeneratedValue(strategy = GenerationType.IDENTITY)</p>
<p>@Column(name=&#8221;user_id&#8221;, unique=true, nullable=false, insertable=true, updatable=true)</p>
<p>public Integer getUserId() {</p>
<p>return user.getUserId();</p>
<p>}</p>
<p>public void setUserId(Integer userId) {</p>
<p>user.setUserId(userId);</p>
<p>}</p>
<p>@Column(name=&#8221;username&#8221;)</p>
<p>public String getUserName() {</p>
<p>return user.getUserName();</p>
<p>}</p>
<p>public void setUserName(String userName) {</p>
<p>user.setUserName(userName);</p>
<p>}</p>
<p>@Column(name=&#8221;password&#8221;)</p>
<p>public String getPassword() {</p>
<p>return user.getPassword();</p>
<p>}</p>
<p>public void setPassword(String password) {</p>
<p>user.setPassword(password);</p>
<p>}</p>
<p>@Column(name=&#8221;state&#8221;)</p>
<p>public Byte getState() {</p>
<p>return user.getState();</p>
<p>}</p>
<p>public void setState(Byte state) {</p>
<p>user.setState(state);</p>
<p>}</p>
<p>}</p></blockquote>
<p><strong> </strong></p>
<p><strong></strong></p>
<p><strong>Step 4: Configuring Hibernate and creating a hibernate mapping file<br />
</strong></p>
<p><strong>I am using mysql DB. Create a file by name hibernate.cfg.xml in the src directory.</strong></p>
<blockquote><p>&lt;?xml version=&#8217;1.0&#8242; encoding=&#8217;UTF-8&#8242;?&gt;</p>
<p>&lt;!DOCTYPE hibernate-configuration PUBLIC</p>
<p>&#8220;-//Hibernate/Hibernate Configuration DTD 3.0//EN&#8221;</p>
<p>&#8220;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&#8221;&gt;</p>
<p>&lt;hibernate-configuration&gt;</p>
<p>&lt;session-factory&gt;</p>
<p>&lt;property name=&#8221;connection.url&#8221;&gt;jdbc:mysql://localhost/myapp_db&lt;/property&gt;</p>
<p>&lt;property name=&#8221;connection.username&#8221;&gt;root&lt;/property&gt;</p>
<p>&lt;property name=&#8221;connection.driver_class&#8221;&gt;com.mysql.jdbc.Driver&lt;/property&gt;</p>
<p>&lt;property name=&#8221;dialect&#8221;&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;</p>
<p>&lt;property name=&#8221;connection.password&#8221;&gt;root&lt;/property&gt;</p>
<p>&lt;property name=&#8221;transaction.factory_class&#8221;&gt;org.hibernate.transaction.JDBCTransactionFactory&lt;/property&gt;</p>
<p>&lt;!&#8211; thread is the short name for org.hibernate.context.ThreadLocalSessionContext and let Hibernate bind the session automatically to the thread &#8211;&gt;</p>
<p>&lt;property name=&#8221;current_session_context_class&#8221;&gt;thread&lt;/property&gt;</p>
<p>&lt;!&#8211; this will show us all sql statements &#8211;&gt;</p>
<p>&lt;property name=&#8221;hibernate.show_sql&#8221;&gt;true&lt;/property&gt;</p>
<p>&lt;mapping package=&#8221;com.myapp.eo&#8221;/&gt;</p>
<p>&lt;mapping class=&#8221;com.myapp.eo.UserEO&#8221;/&gt;</p>
<p>&lt;/session-factory&gt;</p>
<p>&lt;/hibernate-configuration&gt;</p></blockquote>
<p>Now in Hibernate for every database operation you will need a hibernate session.</p>
<p>Usually you do this using some code like below:</p>
<p>Now we have entity mapping and we have also configured the db. Now we need hibernate session to</p>
<p><strong>AnnotationConfiguration cfg = new AnnotationConfiguration();</strong></p>
<p><strong>cfg.addAnnotatedClass(Contact.class);</strong></p>
<p><strong>cfg.configure();</strong></p>
<p><strong>SessionFactory sessionFactory = cfg.buildSessionFactory();</strong></p>
<p><strong>session =sessionFactory.openSession(); </strong></p>
<p>But it is not practical for the entire bean to open multiple sessions to same db for multiple operations. In a complex application you might have number of tables for which you will have number of beans to update/execute query.  So it’s important to make sure all your application share a single session object.</p>
<p>We can accomplish this using a Singleton design pattern. Create a static session object and initialize it in the static block. This ensures that the session will be open before anyone tries to access session object.  The class can look something like this:</p>
<blockquote><p>package com.myapp.hibernate;</p>
<p>import org.hibernate.Session;</p>
<p>import org.hibernate.SessionFactory;</p>
<p>import org.hibernate.cfg.AnnotationConfiguration;</p>
<p>public class HibernateSessionUtil {</p>
<p>private static org.hibernate.SessionFactory sessionFactory;</p>
<p>private HibernateSessionUtil() {</p>
<p>}</p>
<p>static{</p>
<p>sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();</p>
<p>}</p>
<p>public static SessionFactory getInstance() {</p>
<p>return sessionFactory;</p>
<p>}</p>
<p>public Session openSession() {</p>
<p>return sessionFactory.openSession();</p>
<p>}</p>
<p>public Session getCurrentSession() {</p>
<p>return sessionFactory.getCurrentSession();</p>
<p>}</p>
<p>public static void close(){</p>
<p>if (sessionFactory != null)</p>
<p>sessionFactory.close();</p>
<p>sessionFactory = null;</p>
<p>}<br />
<pre>}</pre>
</p></blockquote>
<p>Now we have the utility function ready.</p>
<p>We will also define exceptions which our application might throw. This are the application exceptions, part of business logic. For example in our application if we want to verify a user’s username ans pwd, then if the user is not found , we can throw a UserNotFound exception. If user’s password is not matching we can thorw a UserException with message the password didn’t match. If there is any other (checked) exception the system will wrap it inside a MyAppException and throw it.</p>
<p>Add following classes to the com.myapp.exception package.</p>
<blockquote><p>package com.myapp.exception;</p>
<p>public class MyAppException extends Exception implements java.io.Serializable{</p>
<p>public MyAppException(String msg) {</p>
<p>super(msg);</p>
<p>}</p>
<p>public MyAppException(String msg, Throwable cause) {</p>
<p>super(msg, cause);</p>
<p>}</p>
<p>}</p></blockquote>
<blockquote><p>package com.myapp.exception;</p>
<p>public class UserException extends Exception implements java.io.Serializable{</p>
<p>public UserException(String msg) {</p>
<p>super(msg);</p>
<p>}</p>
<p>public UserException(String msg, Throwable cause) {</p>
<p>super(msg, cause);</p>
<p>}</p>
<p>}</p></blockquote>
<blockquote><p>package com.myapp.exception;</p>
<p>public class UserNotFoundException extends Exception implements java.io.Serializable{</p>
<p>public UserNotFoundException(String msg) {</p>
<p>super(msg);</p>
<p>}</p>
<p>public UserNotFoundException(String msg, Throwable cause) {</p>
<p>super(msg, cause);</p>
<p>}</p>
<p>}</p></blockquote>
<p>Now we need functions for db operations. We do it in the service classess. For each business requirement we can have a service function which will perform the required task and return the results back. An example for user table business actions is shown below. It shows simple select, create and update and delete functions.</p>
<p><strong></strong></p>
<p><strong>Creating the service classes.</strong></p>
<blockquote><p>package com.myapp.service;</p>
<p>import java.util.Iterator;</p>
<p>import java.util.List;</p>
<p>import org.hibernate.HibernateException;</p>
<p>import org.hibernate.Session;</p>
<p>import org.hibernate.Query;</p>
<p>import org.hibernate.Transaction;</p>
<p>import org.apache.commons.logging.Log;</p>
<p>import org.apache.commons.logging.LogFactory;</p>
<p>import com.myapp.accessor.*;</p>
<p>import com.myapp.eo.*;</p>
<p>import com.myapp.vo.*;</p>
<p>import com.myapp.hibernate.*;</p>
<p>import com.myapp.exception.MyAppException;</p>
<p>import com.myapp.exception.UserException;</p>
<p>import com.myapp.exception.UserNotFoundException;</p>
<p>public class UserService {</p>
<p>public User authenticateUser(User user) throws UserException,UserNotFoundException,MyAppException{</p>
<p>Transaction tx = null;</p>
<p>Session session = HibernateSessionUtil.getInstance().getCurrentSession();</p>
<p>try {</p>
<p>tx = session.beginTransaction();</p>
<p>Query q =  session.createQuery(&#8220;select users from UserEO as users where users.userName = :userName&#8221;);</p>
<p>q.setParameter(&#8220;userName&#8221;, user.getUserName());</p>
<p>List users = q.list();</p>
<p>if(users.size() &lt; 1)</p>
<p>throw new UserNotFoundException(&#8220;User Not found&#8221;);</p>
<p>for (Iterator iter = users.iterator(); iter.hasNext();) {</p>
<p>UserEO element = (UserEO) iter.next();</p>
<p>User userVO = element.getUser();</p>
<p>if(!user.getPassword().equals(userVO.getPassword()))</p>
<p>throw new UserException(&#8220;Username and password didnot match&#8221;);</p>
<p>else</p>
<p>user = userVO;</p>
<p>}</p>
<p>tx.commit();</p>
<p>} catch (Exception e) {</p>
<p>if (tx != null &amp;&amp; tx.isActive()) {</p>
<p>try {</p>
<p>// Second try catch as the rollback could fail as well</p>
<p>tx.rollback();</p>
<p>}    catch (HibernateException e1) {</p>
<p>System.out.println(&#8220;Error rolling back transaction&#8221;);</p>
<p>}</p>
<p>// throw again the first exception</p>
<p>}</p>
<p>throw new MyAppException(&#8220;Exception while fetching user data&#8221;,e);</p>
<p>}</p>
<p>return user;</p>
<p>}</p>
<p>public User createUpdateUser(User user) throws MyAppException{</p>
<p>Transaction tx = null;</p>
<p>User userObj = null;</p>
<p>Session session = HibernateSessionUtil.getInstance().getCurrentSession();</p>
<p>try {</p>
<p>UserEO userEO = new UserEO(user);</p>
<p>tx = session.beginTransaction();</p>
<p>userEO = (UserEO)session.merge(userEO);</p>
<p>userObj = userEO.getUser();</p>
<p>tx.commit();</p>
<p>} catch (Exception e) {</p>
<p>if (tx != null &amp;&amp; tx.isActive()) {</p>
<p>try {</p>
<p>// Second try catch as the rollback could fail as well</p>
<p>tx.rollback();</p>
<p>} catch (HibernateException e1) {</p>
<p>System.out.println(&#8220;Error rolling back transaction&#8221;);</p>
<p>}</p>
<p>// throw again the first exception</p>
<p>}</p>
<p>throw new MyAppException(&#8220;Exception while saving user data&#8221;,e);</p>
<p>}</p>
<p>return userObj;</p>
<p>}</p>
<p>public void deleteUser(User user) throws MyAppException{</p>
<p>Transaction tx = null;</p>
<p>Session session = HibernateSessionUtil.getInstance().getCurrentSession();</p>
<p>try {</p>
<p>UserEO userEO = new UserEO(user);</p>
<p>tx = session.beginTransaction();</p>
<p>session.delete(userEO);</p>
<p>tx.commit();</p>
<p>} catch (RuntimeException e) {</p>
<p>if (tx != null &amp;&amp; tx.isActive()) {</p>
<p>try {</p>
<p>// Second try catch as the rollback could fail as well</p>
<p>tx.rollback();</p>
<p>} catch (Exception e1) {</p>
<p>System.out.println(&#8220;Error rolling back transaction&#8221;);</p>
<p>}</p>
<p>}</p>
<p>throw new MyAppException(&#8220;Exception while deleting user data&#8221;,e);</p>
<p>}</p>
<p>}</p>
<p>}</p></blockquote>
<p>The client for this service would be :</p>
<blockquote><p>package com.myapp.client;</p>
<p>import com.myapp.service.*;</p>
<p>import com.myapp.vo.*;</p>
<p>import com.myapp.accessor.*;</p>
<p>public class UserTest {</p>
<p>public static void main(String[] args) throws Exception{</p>
<p>UserService service = new UserService();</p>
<p>User user = new UserVO();</p>
<p>user.setUserName(&#8220;Alex&#8221;);</p>
<p>user.setPassword(&#8220;XXX&#8221;);</p>
<p>try{</p>
<p>User svd = service.authenticateUser(user);</p>
<p>}catch(Exception e){</p>
<p>e.printStackTrace();</p>
<p>}</p>
<p>//create new user</p>
<p>user = new UserVO();</p>
<p>user.setUserName(&#8220;Smitha2&#8243;);</p>
<p>user.setPassword(&#8220;XXX&#8221;);</p>
<p>user.setState((byte)1);</p>
<p>User svdUser = null;</p>
<p>try{</p>
<p>svdUser = service.createUpdateUser(user);</p>
<p>}catch(Exception e){</p>
<p>e.printStackTrace();</p>
<p>}</p>
<p>if(svdUser!=null &amp;&amp; svdUser.getUserId()!=null){</p>
<p>System.out.println(&#8220;svdUser.getUserId() ==&gt;&#8221;+svdUser.getUserId());</p>
<p>svdUser.setPassword(&#8220;YYY&#8221;);</p>
<p>try{</p>
<p>svdUser = service.createUpdateUser(svdUser);</p>
<p>}catch(Exception e){</p>
<p>e.printStackTrace();</p>
<p>}</p>
<p>}</p>
<p>try{</p>
<p>service.deleteUser(svdUser);</p>
<p>}catch(Exception e){</p>
<p>e.printStackTrace();</p>
<p>}</p>
<p>}</p>
<p>}</p></blockquote>
<p>I hope that this <strong>hibernate tutorial </strong>would be helpful to you. Please let us know your comments and feedback</p>
]]></content:encoded>
			<wfw:commentRss>http://www.skill-guru.com/blog/2009/08/17/hibernate-advanced-tutorial-use-hibernate-in-your-java-applications-to-access-database/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Hibernate Tutorial &#8211; Using Annotations with Hibernate</title>
		<link>http://www.skill-guru.com/blog/2009/08/06/hibernate-tutorial-continued-using-annotations/</link>
		<comments>http://www.skill-guru.com/blog/2009/08/06/hibernate-tutorial-continued-using-annotations/#comments</comments>
		<pubDate>Thu, 06 Aug 2009 17:48:17 +0000</pubDate>
		<dc:creator>smitha</dc:creator>
				<category><![CDATA[Programming / tutorials]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[Hibernate Tutorial]]></category>
		<category><![CDATA[using annotations in hibernate]]></category>

		<guid isPermaLink="false">http://www.skill-guru.com/blog/?p=288</guid>
		<description><![CDATA[In case you missed the first post Hibernate Tutorial for beginners , please go through it if you are new to hibernate.
Annotations are powerful and easy way used to provide metadata about the class.They do not effect the operation of the code. They can be used to provide information about the class to the compiler. They can [...]]]></description>
			<content:encoded><![CDATA[<p>In case you missed the first post <a href="http://www.skill-guru.com/blog/2009/08/05/first-hibernate-tutorial-%E2%80%93get-hands-on-experience/" target="_self">Hibernate Tutorial for beginners </a>, please go through it if you are new to hibernate.</p>
<p>Annotations are powerful and easy way used to provide metadata about the class.They do not effect the operation of the code. They can be used to provide information about the class to the compiler. They can be used to replace the configuration files.  Many applications scan files and detect annotated classes and get configured accordingly.  I am using <strong>JPA API</strong> here to demonstrate you the usage of annotations. Please download <strong>ejb3-persistence.jar </strong>and include in your referenced libraries.</p>
<p><span id="more-288"></span></p>
<p>We do not need jboss to run JPA hibernate examples but we can copy these jar files in our webserver and we are good to go.</p>
<p>I hope you have gone through my previous post explaining how to configure and run the first hibernate example because this hibernate tutorial would cover the next steps. There I have used <strong>Conatct.hbm.xml file to map  the </strong>Contact class to the contact table. Below I have explained how we can use annotations to replace the table hbm.xml files in Hibernate.</p>
<p>For beginners, the contact table contains following fields:</p>
<p>Create table CONTACT(<br />
ID int(15),<br />
FIRSTNAME varchar(50) ,<br />
LASTNAME varchar(50),<br />
EMAIL varchar(150));</p>
<p>Change the Contact class as follows:</p>
<p>import javax.persistence.Column;<br />
import javax.persistence.Entity;<br />
import javax.persistence.Id;<br />
import javax.persistence.Table;<br />
import javax.persistence.*;<br />
@Entity<br />
@Table(name=&#8221;contact&#8221;)<br />
public class Contact {<br />
private String firstName;<br />
private String lastName;<br />
private String email;<br />
private long id;</p>
<p>@Column(name=&#8221;FIRSTNAME&#8221;)<br />
public String getFirstName() {<br />
return firstName;<br />
}</p>
<p>public void setFirstName(String string) {<br />
firstName = string;<br />
}</p>
<p>@Column(name=&#8221;LASTNAME&#8221;)<br />
public String getLastName() {<br />
return lastName;<br />
}</p>
<p>public void setLastName(String string) {<br />
lastName = string;<br />
}</p>
<p>@Column(name=&#8221;EMAIL&#8221;)<br />
public String getEmail() {<br />
return email;<br />
}<br />
public void setEmail(String string) {<br />
email = string;<br />
}</p>
<p>@Id<br />
@Column(name=&#8221;ID&#8221;)<br />
public long getId() {<br />
return id;<br />
}</p>
<p>public void setId(long l) {<br />
id = l;<br />
}</p>
<p>}</p>
<p>Remove following lines from hibernate.cfg.xml</p>
<p>&lt;mapping resource=&#8221;contact.hbm.xml&#8221;/&gt;</p>
<p>In above class, we have added</p>
<p>@Entity<br />
@Table(name=&#8221;contact&#8221;)</p>
<p>annotations.</p>
<p>@Entity declares the class as an entity bean. @Table annotation specifies compiler that the table name in db is &#8216;contact&#8217;. If @Table is not specified, then the classname will be considered as table name.</p>
<p>@Column specifies the column name of the table. We specify it for the getter method of the field. If not specified, the field name itself is considered as the column name.</p>
<p>Each table should have a primary key. This will be specified by @Id annotation.</p>
<p>Now we can test the above configuration using the client class as follows:</p>
<p>import org.hibernate.Session;<br />
import org.hibernate.SessionFactory;<br />
import org.hibernate.cfg.AnnotationConfiguration;<br />
import org.hibernate.cfg.Configuration;</p>
<p>public class MyExample {<br />
public static void main(String[] args) {<br />
Session session = null;</p>
<p>try{<br />
// This step will read hibernate.cfg.xml and prepare hibernate for use</p>
<p>AnnotationConfiguration cfg = new AnnotationConfiguration();<br />
cfg.addAnnotatedClass(Contact.class);<br />
cfg.configure();<br />
SessionFactory sessionFactory = cfg.buildSessionFactory();<br />
session =sessionFactory.openSession();</p>
<p>//Create new instance of Contact and set values in it by reading them from form object<br />
System.out.println(&#8220;Inserting Record&#8221;);<br />
Contact contact = new Contact();<br />
contact.setId(3);<br />
contact.setFirstName(&#8220;Smitha&#8221;);<br />
contact.setLastName(&#8220;Rao&#8221;);<br />
contact.setEmail(&#8220;<a href="mailto:smithaxxx@yahoo.com">smithaxxx@yahoo.com</a>&#8220;);<br />
session.save(contact);<br />
System.out.println(&#8220;Done&#8221;);<br />
}catch(Exception e){<br />
System.out.println(e.getMessage());<br />
}finally{<br />
// Actual contact insertion will happen at this step<br />
session.flush();<br />
session.close();</p>
<p>}</p>
<p>}</p>
<p>}<br />
Run MyExample file.</p>
<p><strong>Output would be :</strong><br />
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).<br />
log4j:WARN Please initialize the log4j system properly.<br />
Inserting Record<br />
Done<br />
Hibernate: insert into contact (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)</p>
<p><strong></strong>I hope you would be enjoying these hibernate tutorial. Please give us your feedback.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.skill-guru.com/blog/2009/08/06/hibernate-tutorial-continued-using-annotations/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>First Hibernate Tutorial –Get Hands on Experience -Part I</title>
		<link>http://www.skill-guru.com/blog/2009/08/05/first-hibernate-tutorial-%e2%80%93get-hands-on-experience/</link>
		<comments>http://www.skill-guru.com/blog/2009/08/05/first-hibernate-tutorial-%e2%80%93get-hands-on-experience/#comments</comments>
		<pubDate>Wed, 05 Aug 2009 20:31:20 +0000</pubDate>
		<dc:creator>smitha</dc:creator>
				<category><![CDATA[Programming / tutorials]]></category>
		<category><![CDATA[First Hibernate Tutorial]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[Hibernate and eclipse tutorial]]></category>
		<category><![CDATA[Hibernate Tutorial]]></category>

		<guid isPermaLink="false">http://www.skill-guru.com/blog/?p=259</guid>
		<description><![CDATA[Hibernate Tutorials, First Hibernate Tutorial, Hibernate and eclipse tutorial]]></description>
			<content:encoded><![CDATA[<p style="text-align: left;"><span style="color: #cc0000;"> </span></p>
<p style="text-align: left;"><a class="alignright" href="http://www.skill-guru.com/blog/2009/10/06/hibernate-tutorial-part-ii/" target="_self">Part - II &gt;&gt;</a></p>
<p style="text-align: left;">
<p style="text-align: left;">Hibernate is a powerful, high performance object/relational persistence and query service. It maps database tables to objects so that the database tables can be queried and used as objects.</p>
<p style="text-align: left;">This <strong>hibernate tutorial</strong> gives a step by step solution to develop a first Hibernate application using Eclipse.</p>
<ol>
<li><strong>Requirements:</strong>Eclipse 3, Mysql Database, JDK 1.5, Download hibernate from <a href="https://www.hibernate.org/30.html">https://www.hibernate.org/30.html</a> and unzip it.</li>
<li><strong>Setting Up Project : </strong></li>
</ol>
<p><span id="more-259"></span></p>
<p><strong>Step 1: </strong>Create project.Open Project Wizard and create simple java project</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial1.GIF"><img class="alignnone size-full wp-image-260" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial1.GIF" alt="tutorial1" width="552" height="558" /></a></p>
<p>Next Screen -&gt; New Java Project Screen appears. Enter Project Name.</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial2.GIF"><img class="alignnone size-full wp-image-262" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial2.GIF" alt="tutorial2" width="540" height="703" /></a></p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial1.GIF"></a></p>
<p>Now you can see the project being setup and listed in the package explorer(left)</p>
<p>Step 2:  Add jars to the path Create a user Library</p>
<p>Right click project and select Properties</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial4.GIF"><img src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial4.GIF" alt="tutorial4" width="462" height="853" /></a></p>
<p>Select Libraries</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial5.GIF"><img class="alignnone size-full wp-image-265" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial5.GIF" alt="tutorial5" width="554" height="474" /></a></p>
<p>Click Add Library -&gt; User Library<a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial6.GIF"><img class="alignnone size-full wp-image-266" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial6.GIF" alt="tutorial6" width="720" height="583" /></a></p>
<p>Click Next</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial7.GIF"><img class="alignnone size-full wp-image-267" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial7.GIF" alt="tutorial7" width="764" height="658" /></a></p>
<p>Click userlibraries</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial8.GIF"><img class="alignnone size-full wp-image-268" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial8.GIF" alt="tutorial8" width="781" height="618" /></a></p>
<p>Click New Button to create new userlibrary</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial9.GIF"><img class="alignnone size-full wp-image-269" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial9.GIF" alt="tutorial9" width="750" height="643" /></a></p>
<p>You can see HibernateLib library created</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial10.GIF"><img class="alignnone size-full wp-image-270" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial10.GIF" alt="tutorial10" width="750" height="648" /></a></p>
<p>Open the downloaded and unzipped Hibernate directory and Add jars from downloaded Hibernate 3/lib and hibernate3.jar to HibernateLibrary.</p>
<p>Select TraningProject /lib directory and select all the jars &#8211;&gt; open</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial11.GIF"><img class="alignnone size-medium wp-image-271" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial11-300x187.GIF" alt="tutorial11" width="300" height="187" /></a></p>
<p>Select all jars and click open. You can see jars being selectd as below:</p>
<p><a href="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial12.GIF"><img class="alignnone size-full wp-image-272" src="http://www.skill-guru.com/blog/wp-content/uploads/2009/08/tutorial12.GIF" alt="tutorial12" width="750" height="648" /></a></p>
<p>Click ok &#8211;&gt; Finish &#8211;&gt; Ok.  Now you can see the jars are being added to referenced libraries section in package explorer.</p>
<p>Also download <strong>mysql-connector.jar and include in your library.</strong></p>
<p><strong>Configuring Hibernate</strong></p>
<p>Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.Create a file named hibernate.cfg.xml in src directory. Right click &#8211;&gt;  new &#8211;&gt; file</p>
<p>Copy following contents and save.</p>
<p><strong>&lt;?xml version=&#8217;1.0&#8242; encoding=&#8217;utf-8&#8242;?&gt;<br />
&lt;!DOCTYPE hibernate-configuration PUBLIC<br />
&#8220;-//Hibernate/Hibernate Configuration DTD//EN&#8221;<br />
&#8220;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&#8221;&gt;</strong></p>
<p>&lt;hibernate-configuration&gt;<br />
&lt;session-factory&gt;<br />
&lt;property&gt;com.mysql.jdbc.Driver&lt;/property&gt;<br />
&lt;property&gt;jdbc:mysql://localhost/HibernateTest&lt;/property&gt;<br />
&lt;property&gt;root&lt;/property&gt;<br />
&lt;property&gt;yourPassword&lt;/property&gt;<br />
&lt;property&gt;10&lt;/property&gt;<br />
&lt;property&gt;true&lt;/property&gt;<br />
&lt;property&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;<br />
&lt;property&gt;update&lt;/property&gt;<br />
&lt;!&#8211; Mapping files &#8211;&gt;<br />
&lt;mapping resource=&#8221;contact.hbm.xml&#8221;/&gt;<br />
&lt;/session-factory&gt;<br />
&lt;/hibernate-configuration&gt;</p>
<p>In the above configuration file we specified to use the &#8221; HibernateTest &#8221; <strong>(Replace with your Database name on mysql</strong> ) which is running on localhost and the user of the database is root with password yourPassword (<strong>Replace with your mysql db password</strong>). The dialect property  is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL Database. The <strong>&lt;mapping resource=&#8221;contact.hbm.xml&#8221;/&gt; </strong>property is the mapping for our contact table.</p>
<p><strong> </strong><strong>Mysql Setup:</strong></p>
<p>Login to mysql command line interface.</p>
<p><strong>Create new Database:</strong></p>
<p><strong>mysql&gt; create database HibernateTest;</strong></p>
<p><strong>mysql&gt; connect HibernateTest;</strong></p>
<p><strong> </strong></p>
<p><strong><strong>mysql&gt; </strong>Create table CONTACT(<br />
ID int(15),<br />
FIRSTNAME varchar(50) ,<br />
LASTNAME varchar(50),<br />
EMAIL varchar(150)); </strong></p>
<p>Commit your changes:</p>
<p><strong>mysql&gt; commit;</strong></p>
<p><strong>Creating Persisting Class.</strong></p>
<p><span style="font-size: 11pt; color: black; font-family: Arial;">This class will be used to map to Contact Table:</span></p>
<blockquote><p>public class Contact {<br />
private String firstName;<br />
private String lastName;<br />
private String email;<br />
private long id; public String getEmail() {<br />
return email;<br />
} public String getFirstName() {<br />
return firstName;<br />
} public String getLastName() {<br />
return lastName;<br />
} public void setEmail(String string) {<br />
email = string;<br />
} public void setFirstName(String string) {<br />
firstName = string;<br />
} public void setLastName(String string) {<br />
lastName = string;<br />
} public long getId() {<br />
return id;<br />
} public void setId(long l) {<br />
id = l;<br />
}}</p></blockquote>
<p><strong>Mapping the Contact Object to the Database Contact table</strong></p>
<p>The file contact.hbm.xml is used to map Contact Object to the Contact table in the database. <span style="font-size: 11pt; color: navy; font-family: Arial;">Create a file named contact.hbm.xml.</span><span style="font-size: 11pt; color: navy; font-family: Arial;">Here is the code for contact.hbm.xml:</span></p>
<p>&lt;?xml version=&#8221;1.0&#8243;?&gt;<br />
&lt;!DOCTYPE hibernate-mapping PUBLIC<br />
&#8220;-//Hibernate/Hibernate Mapping DTD 3.0//EN&#8221;<br />
&#8220;<a href="http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd</a>&#8220;&gt;</p>
<p>&lt;hibernate-mapping&gt;<br />
&lt;class name=&#8221;Contact&#8221; table=&#8221;CONTACT&#8221;&gt;<br />
&lt;id name=&#8221;id&#8221; type=&#8221;long&#8221; column=&#8221;ID&#8221; &gt;<br />
&lt;generator/&gt;<br />
&lt;/id&gt;</p>
<p>&lt;property name=&#8221;firstName&#8221;&gt;<br />
&lt;column name=&#8221;FIRSTNAME&#8221; /&gt;<br />
&lt;/property&gt;<br />
&lt;property name=&#8221;lastName&#8221;&gt;<br />
&lt;column name=&#8221;LASTNAME&#8221;/&gt;<br />
&lt;/property&gt;<br />
&lt;property name=&#8221;email&#8221;&gt;<br />
&lt;column name=&#8221;EMAIL&#8221;/&gt;<br />
&lt;/property&gt;<br />
&lt;/class&gt;<br />
&lt;/hibernate-mapping&gt;</p>
<p><strong> </strong><strong>Developing Code to Test Hibernate</strong></p>
<p>Hibernate Session is the main runtime interface between a Java application and Hibernate. First we are required to get the Hibernate Session.<strong>SessionFactory</strong> allows application to create the <strong>Hibernate Sesssion</strong> by reading the configuration from <strong>hibernate.cfg.xml</strong> file.  Then the save method on session object is used to save the contact information to the database:</p>
<p>import org.hibernate.Session;<br />
import org.hibernate.SessionFactory;<br />
import org.hibernate.cfg.Configuration;</p>
<p>public class MyExample {<br />
public static void main(String[] args) {<br />
Session session = null;</p>
<p>try{<br />
// This step will read hibernate.cfg.xml and prepare hibernate for use<br />
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();<br />
session =sessionFactory.openSession();<br />
//Create new instance of Contact and set values in it by reading them from form object<br />
System.out.println(&#8220;Inserting Record&#8221;);<br />
Contact contact = new Contact();<br />
contact.setId(3);<br />
contact.setFirstName(&#8220;Smitha&#8221;);<br />
contact.setLastName(&#8220;Rao&#8221;);<br />
contact.setEmail(&#8220;smithaxxx@yahoo.com&#8221;);<br />
session.save(contact);<br />
System.out.println(&#8220;Done&#8221;);<br />
}catch(Exception e){<br />
System.out.println(e.getMessage());<br />
}finally{<br />
// Actual contact insertion will happen at this step<br />
session.flush();<br />
session.close();</p>
<p>}</p>
<p>}</p>
<p>}</p>
<p><strong>Run the Hibernate project:</strong></p>
<p><strong>right click on the MyExample.java file &#8211;&gt; run &#8211;&gt; java application.</strong></p>
<p><strong>You should see something following:</strong></p>
<p>Output:</p>
<p>log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).</p>
<p>log4j:WARN Please initialize the log4j system properly.</p>
<p>Inserting Record</p>
<p>Done</p>
<p>Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)</p>
<p>Hope this tutorials helps. In Next tutorial I&#8217;ll explain how you can use annotations instead of using mapping file like Contact.hbm.xml.</p>
<p>I am hoping this Hibernate Tutorial would have been helpful to you. Do put in your feedback and comments.</p>
<p>Check <a href="http://www.skill-guru.com/blog/2009/10/06/hibernate-tutorial-part-ii/" target="_self">Part II </a>of this tutorial to get more clarity on how the code worked</p>
<p><a href="http://www.skill-guru.com/blog/2009/10/06/hibernate-tutorial-part-ii/" target="_self">Part - II</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.skill-guru.com/blog/2009/08/05/first-hibernate-tutorial-%e2%80%93get-hands-on-experience/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
	</channel>
</rss>

