Thursday 25 December 2014

GeneratedValue : GenerationType : Generating keys automatically


@Id annotation is used to mark particular field as primary key. You can ask hibernate to generate key for you. There are four different options that JPA (Java persistent API) provides (Hibernate implements JPA).

IDENTITY
SEQUENCE
TABLE
AUTO

Type
Description
IDENTITY
Hibernate assign primary keys for the entity using a database identity column.
SEQUENCE
Hibernate assign primary keys for the entity using a database sequence.
TABLE
Hibernate assign primary keys for the entity using an underlying database table to ensure uniqueness.
AUTO
Hibernate pick an appropriate strategy for the particular database to generate unique key.

Note:
Most of the databases don’t support IDENTITY, SEQUENCE. So take wise decision while using these generation types, because it may cause problem for you while migrating to new databases.


package myFirstHibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.TableGenerator;

@Entity
public class Employee {
  @Id
  @TableGenerator(name = "empId", table = "employeeIdTable", pkColumnName = "empKey", pkColumnValue = "empValue", allocationSize = 1)
  @GeneratedValue(strategy = GenerationType.TABLE, generator = "empId")
  private int id;

  private String firstName;
  private String lastName;
  private String designation;
  private int age;
  private double salary;

  @Lob
  private String description;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getDesignation() {
    return designation;
  }

  public void setDesignation(String designation) {
    this.designation = designation;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  public double getSalary() {
    return salary;
  }

  public void setSalary(double salary) {
    this.salary = salary;
  }

  public String getDescription() {
    return description;
  }

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

}

hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/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/sample</property>
    <property name="connection.username">root</property>
    <property name="connection.password">tiger</property>
    
    <!-- Enable the logging of all the generated SQL statements to the console -->
    <property name="show_sql">true</property>
    
    <!-- Format the generated SQL statement to make it more readable, -->
    <property name="format_sql">false</property>
    
    <!-- Hibernate will put comments inside all generated SQL statements to hint what’s the generated SQL trying to do -->
    <property name="use_sql_comments">false</property>
    
    <!-- This property makes Hibernate generate the appropriate SQL for the chosen database. -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    
    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>
    
    <!-- mappings for annotated classes -->
    <mapping class="myFirstHibernate.Employee" />
    
  </session-factory>
  
</hibernate-configuration>

package myFirstHibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import java.util.Date;

public class TestEmployee {
  
  /* Step 1: Create session factory */
  private static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
    applySettings(configuration.getProperties());
    SessionFactory factory = configuration.buildSessionFactory(builder.build());
        return factory;
    }
  
  public static void main(String args[]){
    Employee emp1 = new Employee();
    emp1.setAge(26);
    emp1.setDesignation("Senior Software Developer");
    emp1.setFirstName("Hari Krishna");
    emp1.setLastName("Gurram");
    emp1.setSalary(80000);
    emp1.setDescription("Whaterver the world i saw yesterday is absolutely different from today");
    
    Employee emp2 = new Employee();
    emp2.setAge(30);
    emp2.setDesignation("Teaching staff");
    emp2.setFirstName("Ritwik");
    emp2.setLastName("Mehenty");
    emp2.setSalary(100000);
    emp2.setDescription("If you are lucky enough to find a way of life you love, you have to find the courage to live it.");
    
    /* To persisit data */
    SessionFactory sessionFactory = getSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(emp1);
    session.save(emp2);
    session.getTransaction().commit();
    session.close();   
  }
}


Run TestEmployee class, you will get output like below.
Hibernate: drop table if exists Employee
Hibernate: drop table if exists hibernate_sequences
Hibernate: create table Employee (id integer not null, age integer not null, description longtext, designation varchar(255), firstName varchar(255), lastName varchar(255), salary double precision not null, primary key (id))
Hibernate: create table hibernate_sequences ( sequence_name varchar(255),  sequence_next_hi_value integer )
Dec 20, 2014 8:44:35 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: select sequence_next_hi_value from hibernate_sequences where sequence_name = 'Employee' for update
Hibernate: insert into hibernate_sequences(sequence_name, sequence_next_hi_value) values('Employee', ?)
Hibernate: update hibernate_sequences set sequence_next_hi_value = ? where sequence_next_hi_value = ? and sequence_name = 'Employee'
Hibernate: insert into Employee (age, description, designation, firstName, lastName, salary, id) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into Employee (age, description, designation, firstName, lastName, salary, id) values (?, ?, ?, ?, ?, ?, ?)


Open MySQL prompt, and check employee table

mysql> select * from employee;
+----+-----+--------------------------------------------------------------------------------------------------+---------------------------+--------------+----------+--------+
| id | age | description                                                                                      | designation               | firstName    | lastName | salary |
+----+-----+--------------------------------------------------------------------------------------------------+---------------------------+--------------+----------+--------+
|  1 |  26 | Whaterver the world i saw yesterday is absolutely different from today                           | Senior Software Developer | Hari Krishna | Gurram   |  80000 |
|  2 |  30 | If you are lucky enough to find a way of life you love, you have to find the courage to live it. | Teaching staff            | Ritwik       | Mehenty  | 100000 |
+----+-----+--------------------------------------------------------------------------------------------------+---------------------------+--------------+----------+--------+
2 rows in set (0.00 sec)


As you see employee id’s are generated by Hibernate automatically.



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment