0
Sponsored Links


Ad by Google
Again,we are going to create a step by step very basic hibernate 4 annotation based CRUD application using maven. We have already created the same application without using maven here. In this project we have a single table called user and we are going to perform crud operations on the user table data only.

Technologies & Tools we are using here:

  • JDK 7
  • Hibernate 4.0
  • MySql 5.5
  • Eclipse Juno 4.2
  • Maven 3.2.2
Note: please make sure that maven plugin is installed in your eclipse.

Overview of the project structure:


Main Objects of this project are:
  • pom.xml
  • 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 Maven Project:
Step A: Go to File->New->Other..

Step B: Select Maven Project from the select wizard.

Step C: Select project name and location from New Maven Project wizard.

Step D: Configure project, provide GroupId, artifactId etc. See the details from the screenshot.


Step E: After completion of all the above steps, now your project will looks like this screenshot.


3. Add project dependencies into pom.xml file:

Double click on your project's pom.xml file it will looks like this with very limited information.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hibernate.maven.day1</groupId>
	<artifactId>H4MA_Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Hibernate4 Maven Annotation Example</name>
	<description>Hibernate4 Maven Annotation CRUD Example	</description>
<project

Now add hibernate and mysql dependency, paste the below code in side the project tag.

<dependencies>
		<!-- Hibernate Dependency -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.0.0.Final</version>
		</dependency>
		
		<!-- MySql Connector dependency -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.10</version>
		</dependency>

</dependencies>
That's it, below is the complete pom.xml file

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hibernate.maven.day1</groupId>
	<artifactId>H4MA_Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Hibernate4 Maven Annotation Example</name>
	<description>Hibernate4 Maven Annotation CRUD Example	</description>

	<dependencies>
		<!-- Hibernate Dependency -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.0.0.Final</version>
		</dependency>
		
		<!-- MySql Connector dependency -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.10</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Optional step: If any error showing in your project, then update the project. Right click on your project, go to Maven select Update Project. See the screenshot.


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


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">
  
<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 annotated class -->
        <mapping class="com.hibernate.maven.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.hibernate.maven.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 Hibernate Utility class to Build SessionFactory:

HibernateUtility .java

package com.hibernate.maven.day1.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 a DAO class to insert/update/select/delete records into MySql database:

UserDAO.java

package com.hibernate.maven.day1.dao;


import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hibernate.maven.day1.pojo.User;
import com.hibernate.maven.day1.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 a Service class to call all the methods of UserDAO class:

UserService.java

package com.hibernate.maven.day1.service;

import com.hibernate.maven.day1.dao.UserDAO;
import com.hibernate.maven.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);
  user.setUserName("info@javamakeuse.com");
  
  // calling update method to update the record into db.
  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

Download the same project without using maven from the hereSource Code Without using Maven


Sponsored Links

0 comments:

Post a Comment