Wednesday, April 20, 2016

Basic Annotations and HIbernate Example 1

hibernate.cfg.xml - Hibernate Configuration 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>

        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@172.16.7.236:20300:prtp</property>
        <property name="connection.username">MOBI_CLEANUP_TEST1</property>
        <property name="connection.password">MOBI_CLEANUP_TEST1</property>

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

        <!-- Enable Hibernate's automatic session context management, by default its  update -->
       
        <property name="hbm2ddl.auto">update</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
              <mapping class="org.javadsalgo.dto.UserDetailsDTO"/>
              <!-- <mapping resource="org/javadsalgo/model/UserDetailsDTO.hbm.xml" /> -->
    </session-factory>

</hibernate-configuration>


UserDetailsDTO.java

package org.javadsalgo.dto;

@Entity(name = "USER_DETAILS")
public class UserDetailsDTO implements java.io.Serializable {

      private static final long serialVersionUID = 1L;

      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      @Column(name = "USER_ID")
      private int userId;

      @Column(name = "USER_NAME")
      private String userName;

      @Temporal(TemporalType.DATE)
      private Date createdOn;

      private String Address;

      @Lob
      private String description;

      public Date getCreatedOn() {
            return createdOn;
      }

      public void setCreatedOn(Date createdOn) {
            this.createdOn = createdOn;
      }

      public String getAddress() {
            return Address;
      }

      public void setAddress(String address) {
            Address = address;
      }

      public String getDescription() {
            return description;
      }

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

      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;
      }

}

It is important to note that each @Entity needs to be annotated with @Id which will be the primary key in table. If you don't want your entity to be persisted in a separate table, but rather be a part of other entities, you can use @Embeddable instead of @Entity.

If @Id is missing, it'll throw org.hibernate.AnnotationException: No identifier specified for entity 

HibernateTest.java

package org.javadsalgo.test;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.javadsalgo.dto.UserDetailsDTO;

public class HibernateTest {

      public static void main(String[] args) {
            UserDetailsDTO user =new UserDetailsDTO();
           
            //user.setUserId(1);
            user.setUserName("Abc");
            user.setAddress("722/18 Shastri Nagar , Rohtak");
            user.setCreatedOn(new Date());
            user.setDescription("Hey ,Hibernate is Amazing");
           
            SessionFactory sessionFactory = new                                    Configuration().configure().buildSessionFactory();
            Session session = sessionFactory.openSession();
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
            session.close();
           
            session = sessionFactory.openSession();
            session.beginTransaction();
            user=(UserDetailsDTO) session.get(UserDetailsDTO.class, 1);
            System.out.println("Name is "+user.getUserName()+"\nAddress             is  "+ user.getAddress());
            session.close();
           
      }
}

UserDetailsDTO.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">
<hibernate-mapping>
       <class name="org.javadsalgo.dto.UserDetailsDTO"
              table="USER_DETAILS_HBM">
              <composite-id>       
                     <key-property name ="userId" column = "USER_ID" />
              </composite-id>
              <property name="userName" column="USER_NAME" />
              <property name="createdOn" column="CREATED_ON" type="java.util.Date"/>
              <property name="description" column="DESCRIPTION" />         
       </class>
</hibernate-mapping>

Output :
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into USER_DETAILS (Address, createdOn, description, USER_NAME, USER_ID) values (?, ?, ?, ?, ?)
Hibernate: select userdetail0_.USER_ID as USER1_0_0_, userdetail0_.Address as Address0_0_, userdetail0_.createdOn as createdOn0_0_, userdetail0_.description as descript4_0_0_, userdetail0_.USER_NAME as USER5_0_0_ from USER_DETAILS userdetail0_ where userdetail0_.USER_ID=?
Name is Abc
Address is  722/18 Shastri Nagar , Rohtak


No comments:

Post a Comment