0
Sponsored Links


Ad by Google

In this post we are going to create a step by step very basic hibernate4 annotation based CRUD application. We have already created the same application using hbm.xml mapping file here. In this project we have a single table called user and we are going to play with user table only.

Technologies/Tools we are using here:

  • JDK 7
  • Hibernate 4.0
  • MySql 5.5
  • Eclipse Juno 4.2
Overview of the Project Structure:
Project structure























Main Objects of this project are:
  • Jar files
  • hibernate.cfg.xml
  • Annotated Entity class
  • Database

Here is a user table description  with very few columns:

1. Create table query:
/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

2. Create a Java project


Create a lib folder (Optional): Right click on your project and create a new folder named it as lib,this step is optional this is just to place all the required jar files. You may put all the required jar files anywhere in your system's location. In this project we are putting all the jar files in lib folder.

3. Add libraries(jar files) into project's build path:

Required jar files are:
  • antlr-2.7.7.jar
  • commons-collections-3.2.1.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.0.0.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.12.1.GA.jar
  • jboss-logging-3.1.0.CR2.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.3-rc-bin.jar

Right click on your project go to Build Path > Configure Build Path:


Now, Click on libraries, If you placed all the required jar files in side the lib folder of the project, then click on Add Jars otherwise click on Add External JARs. and select the jar files.

4. Create a hibernate.cfg.xml file:

Create a hibernate.cfg.xml configuration file inside your src folder. Minimum properties required inside hibernate.cfg.xml file are:
  • connection.driver_class
  • connection.url
  • connection.username
  • connection.password
  • dialect
  • mapping class

Complete hibernate.cfg.xml 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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
         
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
  
        <mapping class="com.annotation.day1.pojo.User"/>
          
    </session-factory>
</hibernate-configuration>

5. Create Annotated Entity class:

Now create User.java annotated class, we have a user table so we created User.java class (not mandatory to create tablename.java you may create xyz.java class also).

Here is a Complete User.java class:

package com.annotation.day1.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="user")
public class User {

 @Id
 @Column(name="id")
 private int userId;
 
 @Column(name="user_name")
 private String userName;
 
 @Column(name="password")
 private String password;

 public int getUserId() {
  return userId;
 }

 public void setUserId(int userId) {
  this.userId = userId;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 @Override
 public String toString() {
  return "User [userId=" + userId + ", userName=" + userName
    + ", password=" + password + "]";
 }

}

6. Create a Utility class to Build SessionFactory:

HibernateUtility .java

package com.annotation.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtility {
  private static final SessionFactory sessionFactory = buildSessionFactory();
     private static SessionFactory buildSessionFactory() {
     
      Configuration configuration = new Configuration();
      configuration.configure();

      ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().
      applySettings(configuration.getProperties()).buildServiceRegistry();
      SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
   return sessionFactory;
     }
   
     public static SessionFactory getSessionFactory() {
         return sessionFactory;
     }
}

7. Create DAO class to insert/update/select/delete records into MySql database:

UserDAO.java

package com.annotation.day1.dao;


import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hbm.day1.pojo.User;
import com.hbm.util.HibernateUtility;

public class UserDAO {
 private static SessionFactory sessionFactory;
 static {
  sessionFactory = HibernateUtility.getSessionFactory();
 }

 public static User findById(int id) {
  Session session = sessionFactory.openSession();
  User user = (User) session.get(User.class, id);

  return user;
 }

 public static User save(User user) {
  Session session = sessionFactory.openSession();

  session.beginTransaction();

  session.save(user);

  session.getTransaction().commit();

  return user;
 }

 public static User update(User user) {
  Session session = sessionFactory.openSession();

  session.beginTransaction();

  session.merge(user);

  session.getTransaction().commit();

  return user;

 }

 public static void delete(User user) {
  Session session = sessionFactory.openSession();

  session.beginTransaction();

  session.delete(user);

  session.getTransaction().commit();

 }
 
 @SuppressWarnings("unchecked")
 public static List<User> findAll(){
  Session session = sessionFactory.openSession();
   return session.createQuery("from User").list();
  
 }
}

8. Create UserService class to call all the methods of UserDAO class:

UserService.java

package com.annotation.day1.service;

import com.annotation.day1.dao.UserDAO;
import com.annotation.day1.pojo.User;

public class UserService {

 public static void main(String[] args) {
  User user = new User();
  user.setPassword("xxx");
  user.setUserName("tony");
  
  // calling save method to insert record into db.
  UserDAO.save(user);
  
  // calling findById method to select record from the db.
  user = UserDAO.findById(1);
  
  // calling update method to update the record into db.
  user.setUserName("info@javamakeuse.com");
  UserDAO.update(user);
  
  // calling findAll method to select all the records from the db.
  System.out.println(UserDAO.findAll());
  
  // calling delete method to delete the record from the db.
  UserDAO.delete(user);
 }
}


Finally, run the UserService class and see the output, you will get the output at your console.

OUT PUT:
  • Hibernate: insert into user (password, user_name, id) values (?, ?, ?)
  • Hibernate: select user0_.id as id0_0_, user0_.password as password0_0_, user0_.user_name as user3_0_0_ from user user0_ where user0_.id=?
  • Hibernate: select user0_.id as id0_0_, user0_.password as password0_0_, user0_.user_name as user3_0_0_ from user user0_ where user0_.id=?
  • Hibernate: update user set password=?, user_name=? where id=?
  • Hibernate: select user0_.id as id0_, user0_.password as password0_, user0_.user_name as user3_0_ from user user0_
  • [User [userId=1, userName=info@javamakeuse.com, password=xxx]]
  • Hibernate: select user_.id, user_.password as password0_, user_.user_name as user3_0_ from user user_ where user_.id=?
  • Hibernate: delete from user where id=?

Note: If you notice at your console output, here it's printing sql statements also, because we are printing this using <property name="show_sql">true</property> in hibernate.cfg.xml file to hide this statements make it false from true or remove the complete line.

Download the Complete example from here Source Code

For required jar files you may download it from hibernate.org or from my previous post, here.
Sponsored Links

0 comments:

Post a Comment