0
Sponsored Links


Ad by Google
In hibernate generator class is used to generate unique identifiers for instances of the persistence class. Hibernate provides the list of built in generator classes to generate unique identifiers, all the generator classes implements the org.hibernate.id.IdentifierGenerator interface, and if your needs of unique identifiers is not solved by using built in generator classes, then you can create your own generator classes by implementing org.hibernate.id.IdentifierGenerator interface. Here is a example of custom generator class via implementing org.hibernate.id.IdentifierGenerator interface.

The default generator class provided by hibernate is assigned, If you explicitly not provide any <generator> element then hibernate will used assigned as the <generator> element. If we are using assigned as our generator class, then we must have to explicitly provide the primary key values of the persistence object before the object get persist.

Lets create a simple project to see the use of assigned generator class.
Here is our generator table ER-Diagram, we are using for this project.

Tools and Technologies we are using here:

  • JDK 7
  • Hibernate 4.3.7
  • MySql 5.1.10
  • Eclipse Juno 4.2
  • Maven 3.2
Overview of the Project Structure:


Main Objects of this project are:
  • pom.xml
  • hibernate.cfg.xml
  • Generator.hbm.xml
  • database

Step 1. Create a maven project and add the below given dependencies for hibernate and mysql, inside your pom.xml file.
<dependencies>
  <!-- Hibernate Dependency -->
  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>4.3.7.Final</version>
  </dependency>
  
  <!-- MySql Connector dependency -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.10</version>
  </dependency>

 </dependencies>

Step 2. Create a hibernate.cfg.xml file:
Create hibernate.cfg.xml file inside src/main/resources folder.

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/hibernate_tutorial</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>
     <property name="hbm2ddl.auto">update</property>
        <mapping resource="Generator.hbm.xml"/>
          
    </session-factory>
</hibernate-configuration>

Step 3. Create Generator.hbm.xml mapping file inside src/main/resources folder. See the child element of id is generator element and we are using here assigned as the value of generator.

Generator.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">
<!-- Generated 29 Oct, 2014 8:47:37 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.hibernate.generator.pojo.Generator" table="generator">
        <id name="generatorId" type="java.lang.Integer" column="generator_id" >
            <generator class="assigned"></generator>
  </id>
        <property name="generatorName" column="generator_name">
            <type name="org.hibernate.type.EnumType">
           <param name="enumClass">com.hibernate.generator.util.GeneratorType</param>
           <param name="type">12</param>
        </type>
        </property>
        <property name="description" column="description"/>
    </class>
</hibernate-mapping>

Step 4. Create HibernateUtility.java class to return SessionFactory in hibernate 4.3.7

HibernateUtility.java

package com.hibernate.generator.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtility {
 private static final SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory() {
  Configuration configuration = new Configuration();
  configuration.configure();

  ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
    .applySettings(configuration.getProperties()).build();
  SessionFactory sessionFactory = configuration
    .buildSessionFactory(serviceRegistry);

  return sessionFactory;
 }

 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}

Step 5. Create GeneratorType Enum, GeneratorType is a data type for our generator_name column. This is just a data type we are using here instead of varchar, in our generator table we are using enum, so we have created an Enum type to mapped the generator_name property.

GeneratorType
package com.hibernate.generator.util;

public enum GeneratorType {
IDENTITY, INCREMENT, HILO, ASSIGNED, NATIVE, UUID, GUID, SELECT
}

Step 6. Create Generator.java pojo class, It has all the properties defined inside the Generator.hbm.xml file.

Generator
package com.hibernate.generator.pojo;

import com.hibernate.generator.util.GeneratorType;

public class Generator {

 private int generatorId;
 private GeneratorType generatorName;
 private String description;

 public int getGeneratorId() {
  return generatorId;
 }

 public void setGeneratorId(int generatorId) {
  this.generatorId = generatorId;
 }

 public GeneratorType getGeneratorName() {
  return generatorName;
 }

 public void setGeneratorName(GeneratorType generatorName) {
  this.generatorName = generatorName;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }

 @Override
 public String toString() {
  return "Generator [generatorId=" + generatorId + ", generatorName="
    + generatorName + ", description=" + description + "]";
 }

}

Step 7. Create GeneratorDAO.java class and provide the implementation of CRUD method.

GeneratorDAO
package com.hibernate.generator.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.hibernate.generator.pojo.Generator;
import com.hibernate.generator.util.HibernateUtility;

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

 public static Generator findById(long id) {
  Session session = sessionFactory.openSession();
  Generator generator = (Generator) session.load(Generator.class, id);

  return generator;
 }

 public static Generator save(Generator generator) {
  Session session = sessionFactory.openSession();

  session.beginTransaction();

  session.save(generator);

  session.getTransaction().commit();

  return generator;
 }

 public static Generator update(Generator generator) {
  Session session = sessionFactory.openSession();

  session.beginTransaction();

  session.merge(generator);

  session.getTransaction().commit();

  return generator;

 }

 public static void delete(Generator generator) {
  Session session = sessionFactory.openSession();

  session.beginTransaction();

  session.delete(generator);

  session.getTransaction().commit();

 }
}

Step 8. Create GeneratorService.java class to call the methods of GeneratorDAO class

GeneratorService
package com.hibernate.generator.service;

import com.hibernate.generator.dao.GeneratorDAO;
import com.hibernate.generator.pojo.Generator;
import com.hibernate.generator.util.GeneratorType;

public class GeneratorService {
 public static void main(String[] args) {
  Generator generator = new Generator();
  generator.setDescription("assigned generator class used");
  // here we have assigned the primary key value
  generator.setGeneratorId(999);
  generator.setGeneratorName(GeneratorType.ASSIGNED);
  System.out.println(GeneratorDAO.save(generator));
 }
}

Run the GeneratorService, It will create a new record inside the generator table of hibernate_tutorial database. Here we have assigned the primary key value as 999.

OUT PUT:
Hibernate: insert into generator (generator_name, description, generator_id) values (?, ?, ?)
Generator [generatorId=999, generatorName=ASSIGNED, description=assigned generator class used]

Download the complete example from here Source Code


Sponsored Links

0 comments:

Post a Comment