Tuesday, June 11, 2013

04 - hbm2ddl-Configuration-and-Name-Annotations


In this tutorial, we'll look at the schema generation options in Hibernate. We'll also learn some annotations to change the default name generated by Hibernate for entities.

Below configuration always deletes old DB schema and recreates new DB schema.
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>  <!-- create / update -->
                               
Below configuration always updates DB.
<!-- Names the annotated entity class -->
<mapping class="org.yash.dto.UserDetails"/>    
                               
Below configuration will display SQL queries in log and console
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

Below annotation is used to create DB with name "USER_DETAILS" instead of class name
@Entity (name="USER_DETAILS")

Below annotation is used to create column with NAME “USER_NAME”.
@Column (name="USER_NAME")

You can add columns names and primary key as below which is at top of the getter Methods instead of class variables.
                @Id
                @Column (name="USER_id")
                public int getUserId() {
                                return userId;
                }

                @Column (name="USER_NAME")          
                public String getUserName() {
                                return userName;
                }


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>

        <property name="connection.driver_class">
org.postgresql.Driver
  </property>
        <property name="connection.url">
jdbc:postgresql://localhost:5433/hibernated
  </property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">admin</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">
            org.hibernate.dialect.PostgreSQLDialect
        </property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
       
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
       
        <!-- Drop and re-create the database schema on startup -->
            <property name="hbm2ddl.auto">create</property> 
  <!-- create / update -->
   
        <!-- Names the annotated entity class -->
        <mapping class="org.yash.dto.UserDetails"/>  

    </session-factory>

</hibernate-configuration>

UserDetails.java
package org.yash.dto;

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

@Entity (name="USER_DETAILS")
public class UserDetails {

      private int userId;
      private String userName;

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

      @Id
      @Column (name="USER_ID")
      public int getUserId() {
            return userId;
      }
      public void setUserName(String userName) {
            this.userName = userName;
      }
     
      @Column (name="USER_NAME")
      public String getUserName() {
            return userName + "from getter";
      }
}

HibernateTest.java
package org.yash.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.yash.dto.UserDetails;

public class HibernateTest {

      public static void main(String args[]){
            UserDetails user = new UserDetails();
            user.setUserId(3);
            user.setUserName("Third User");
           
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
           
            Session session = sessionFactory.openSession();
            /* It is used to save all the objects and to define single unit of work */
            session.beginTransaction();
           
            session.save(user);
            session.getTransaction().commit();
      }
}

                               

No comments:

Post a Comment