@Id @GeneratedValue(strategy=GenerationType.AUTO)
  private int userId;

By using @GeneratedValue annotation we can create primary key in table.The annotations takes 4 parameter as strategy attribute.

@GeneratedValue(strategy=GenerationType.AUTO)
Auto tells the Hibernate to do the primary key addition from hibernate side

@GeneratedValue(strategy=GenerationType.IDENTITY)
IDENTITY tells the Hibernate to do the primary key addition from DB side when set to auto increment.

@GeneratedValue(strategy=GenerationType.SEQUENCE)
SEQUENCE tells the Hibernate to do the primary key addition as defined by sequence in DB.

@GeneratedValue(strategy=GenerationType.TABLE)
TABLE tells the Hibernate to create a seperate table in DB and maintain the last inserted values.
The table contains only one row with last inserted value.

15

Retrieve value from Database using Session

public static void main(String[] args)
{
	UserDetails objUserDetail =  new UserDetails();
	.
	session.getTransaction().commit();

	objUserDetail = null;

	/*Retriving UserDetails from DB Using Session*/
	session = sessionFact.openSession();
	session.beginTransaction();
	objUserDetail = (UserDetails)session.get(UserDetails.class, 105);
	System.out.println(objUserDetail.getUserName());
}

To retrieve the value from session we use the primary key for the table in the above case.

 objUserDetail = (UserDetails)session.get(UserDetails.class, 105);
 System.out.println(objUserDetail.getUserName());

105 – is the UserId which is primary key for the USER_DETAILS table in DB.

Defining Dialect in Hibernate

MySQL Dialect
MySQL Dialect

<!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>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">pass</property>
        
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

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

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</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">update</property>
        
        <!-- Name of the Annotated Entity class -->
        <mapping class="com.mugil.dto.UserDetails"/>
    </session-factory>
</hibernate-configuration>

If hbm2ddl.auto is set to create the table will be created every time when java class is Run.The old records will be deleted.

<property name="hbm2ddl.auto">create</property>

When set to update the records will be added without new table creation

<property name="hbm2ddl.auto">update</property>

More Annotations

3

@Transient tells not to create Column
@Column tells the Hibernate the Name under which column need to be
created in Db table.

@Transient 
@Column (name="User_Name") 
private String userName; 

@Temporal tells the option of selective addition.Below I am adding Date rather than
Date & time as Timestamp

 @Temporal (TemporalType.DATE) 
 private Date DOJ;

@Lob – Large Object, Telling Hibernate to create Large Object Datatype fro Column
@Lob over String creates CLOB
@Lob over Byte creates BLOB

 @Lob
 private String userDescription;

Simple Hibernate Table Creation from Scratch

Hibernate Required Jar Files List
Hibernate Required Jar Files List

Step1: Create a Bean for which Table should be created in Database
Step2: Create a Class which uses the bean.

Step 1

package com.mugil.dto;

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

@Entity 
public class UserDetails {
	@Id	
	private int userId;
	private String userName;
	
	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;
	}
}

Step 2

package com.mugil.access;

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

import com.mugil.dto.UserDetails;

public class CreateUser {
	private static ServiceRegistry serviceRegistry;
	private static SessionFactory sessionFactory;
	
	public static void main(String[] args) {
		UserDetails objUserDetail =  new UserDetails();
		objUserDetail.setUserId(101);
		objUserDetail.setUserName("Mugil");
		
		SessionFactory sessionFact = createSessionFactory();
		Session session = sessionFact.openSession();
		session.beginTransaction();
		session.save(objUserDetail);
		session.getTransaction().commit();	
	}
	
	
	public static SessionFactory createSessionFactory() {
	    Configuration configuration = new Configuration();
	    configuration.configure();
	    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
	            configuration.getProperties()).build();
	    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	    return sessionFactory;
	}
}

In Some cases the hibernate.cfg.xml might become unrecognized.In such case the code should be changed to force the config to be picked from the file location.

public static SessionFactory createSessionFactory() 
{
  Configuration configuration = new Configuration().configure();	  
  configuration.configure("hibernate.cfg.xml");	  
  configuration.addAnnotatedClass(com.mugil.tutor.UserDetails.class);
	  
  serviceRegistry = new   StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
  sessionFactory = configuration.buildSessionFactory(serviceRegistry);
  return sessionFactory;
}

Hibernate uses SessionFactory pattern internally as below

SessionFactory sessionFact = createSessionFactory();
Session session = sessionFact.openSession();
session.beginTransaction();
session.save(objUserDetail);
session.getTransaction().commit();	

1.Create Object for SessionFactory
2.Open Session to begin Transaction
3.Begin Transaction using beginTransaction() Method
4.Save the Object by Passing Object of the bean
5.Complete the Transaction using commit

Annotations
@Entity – Means entity as a whole>table would be created by the Name of the Entity
@Id – Tells the Primary Key

Having a Different table name from Class Name
Annotations

@Entity(name="User_Details")
public class Users 
{
 .
 .
}

Table with User_Details would be created instead of Users

Having a Different Column name from Object Name
Annotations

@Entity(name="User_Details")
public class Users 
{
 @Id
 @Column(name="USER_ID")
 private String UserId;
 .
 .
}

Columns with User_Id would be created instead of UserId

Appending String to Getters

public void setName(String name) 
{
  Name = name + " Append Test ";
}

Appending String to Getters

@Entity
@Table (name="User_Details")
public class Users 
{

}

The Entity Name Still remains the same but the table Name is different.

@Basic Annotation – Tells Hibernate to persist which it does by default

public class Users 
{
 @Basic
 private String UserName;
 . 
 .
}

@Basic has 2 Parameters – Fetch, optional. The only time you use @Basic is while applying the above options.

@Transient Annotation – Tells Hibernate to not store data in database

public class Users 
{
 @Transient
 private String UserName;
 . 
 .
}

@Temporal Annotation – Tells Hibernate to specify Date or Time

public class Users 
{
 @Temporal (TemporalType.Date)
 private String joinedDate;
 . 
 .
}

Without @Temporal the joinedDate is store along with TimeStamp in DB. Now using TemporalType(which is ENUM) you can select the type of data which can be stored in Database.

@Lob – Tells Hibernate to specify Date or Time

public class Users 
{
 @Lob
 private String Address;
 . 
 .
}

Tells the database field should be created as CLOB instead of VARCHAR(255).

For setting the Bean value in struts-config.xml we should use the form-beans tag.The form-beans tag might contain any number of bean property defined within form-bean as below.

Defining a Simple Bean Property

<form-beans>
 <form-bean name="userBean" type="org.apache.struts.action.DynaActionForm">
   <form-property name="userName" initial="This is Bean Value" type="java.lang.String" />	
 </form-bean>
</form-beans>

In the above code I am creating a userBean and setting its value is initialized to This is Bean Value.

Now in the action mapping part of the struts-config.xml I am going to map the above created bean to path as said below

<action-mappings>
 <action path="/showBeanValue" type="org.apache.struts.actions.ForwardAction" parameter="/showBeanValue.jsp"/>				
 <action name="userBean" path="/Login" />		
</action-mappings>

In the first line I am defining action path as showBeanValue and it is going to forward to page showBeanValue.jsp when some one access the showBeanValue.do in url.

In the second statement I am creating a dummy form since the the html form action should not be empty.

 
  <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
  <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>     
  <html:form action="/Login">
    <bean:write name="userBean" property="userName"></bean:write>
    <bean:write name="userBean" property="userAge"></bean:write>
  </html:form>

Running Iterator Through Bean Stored in Map List

public class Iterator extends ActionSupport
{
   Map nmap = new HashMap<String, List<Person>>();
	
   public String execute()
   {
      Person objPerson    = new Person();

      objPerson.userName  = "Name1";
      objPerson.age 	    = 25;
      List<Person> myList = new ArrayList<Person>();
      myList.add(objPerson);
		
      nmap.put("Mugil", myList);
	
      objPerson.userName   = "Name2";
      objPerson.age 	     = 26;
      List<Person> myList2 = new ArrayList<Person>();
      myList2.add(objPerson);
		
      nmap.put("Mani", myList2);
		
      objPerson.userName    = "Name3";
      objPerson.age 	      = 27;
      List<Person> myList3  = new ArrayList<Person>();
      myList3.add(objPerson);
		
      nmap.put("Vinu", myList3);
		
      setNmap(nmap);
		
      return SUCCESS;
   }
	
   public Map getNmap() 
   {
     return nmap;
   }

   public void setNmap(Map nmap) 
   {
     this.nmap = nmap;
   }
}

Person Bean Code

class Person
{
    String userName;
    int age;

    public int getAge() {
      return age;
    }

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

    public String getUserName() {
      return userName;
    }
	
    public void setUserName(String userName) {
      this.userName = userName;
    }
}

JSP Page Using Struts2 Tag

<table>
<s:iterator value="nmap">
     <s:iterator var="Person" value="value">
      <tr>
     	<td>
    	  <s:property value="key" />	
    	</td>
        <td>
      	  <s:property value="age" />
    	</td>
      </tr>
      </s:iterator>
</s:iterator>
</table>

Action Class Code

public class DropDown extends ActionSupport{
    private List arrUserDetails = new ArrayList<Users>();

    public DropDown()
    {
        Users objUsers = new Users();
        objUsers.setUserId("101");
        objUsers.setUserName("User1");

        arrUserDetails.add(objUsers);

        objUsers.setUserId("102");
        objUsers.setUserName("User2");

        arrUserDetails.add(objUsers);

        objUsers.setUserId("103");
        objUsers.setUserName("User3");

        arrUserDetails.add(objUsers);
    }

    public String execute(){
        return SUCCESS;
    }

    public List getArrUserDetails() {
        return arrUserDetails;
    }


    public void setArrUserDetails(List arrUserDetails) {
        this.arrUserDetails = arrUserDetails;
    }
}

Users Bean Class

 public class Users
{
    private String userId;
    private String userName;

    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}

JSP Page Struts2 Tag

 <s:select label="Departments" list="departmentList" listKey="deptId" listValue="deptName" name="department"/>