=CONCATENATE(B2,".",C2,".",D2)

--Update Script
  =CONCATENATE("UPDATE Location SET Location_Description = '", D2, "'  WHERE  LOCATION_CODE ='", B2,"' AND LOCATION_NAME ='", C2, "'")
 UPDATE Location 
   SET Location_Description = 'Thats where I Live'
 WHERE LOCATION_CODE = '600018'
   AND LOCATION_NAME = 'Teynampet'

DBUtilsTest.java

public class DBUtilsTest
{	
	public void getDBRecordsSQLTest()
	{	
		DBUtils objDBUtils 	 = new DBUtils();
		ResultSet resultSet  = objDBUtils.getDBRecordsSQL("SELECT 78985450.1245487986418648 decimal_val FROM dual");
		
		double expectedValue   = 1245.654618764;
		double dbValue 	 	   = 0; 
		double toleranceLimit  = 0.000000001;
		
		try
		{
			 while(resultSet.next())
			 {
				dbValue =  resultSet.getDouble("decimal_val");
				assertEquals(expectedValue, dbValue, toleranceLimit);
			 }
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		objDBUtils.closeConnection();
	}
	
	@Test
	public void getDBRecordsProcTest()
	{	
		DBUtils objDBUtils 	 = new DBUtils();
		ResultSet resultSet  = objDBUtils.getDBRecordsProc("{call TESTJUNIT.junitproc(?)}");
		
		double expectedValue   = 7.89854501245488E7;
		double dbValue 	 	   = 0; 
		double toleranceLimit  = 0.000000001;
		
		try
		{
			 while(resultSet.next())
			 {
				dbValue =  (double) resultSet.getDouble(1);				
				assertEquals(expectedValue, dbValue, toleranceLimit);
			 }
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		objDBUtils.closeConnection();
	}
}

DBUtils.java

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.jdbc.OracleTypes;

public class DBUtils
{
	Connection  conn  = null;
    Statement 	stmt  = null;
    ResultSet   rs    = null;
	
	public ResultSet getDBRecordsSQL(String pQuery)
	{    
	    try
	    {
	    	conn = DriverManager.getConnection("hostname", "admin", "admin123");
	        stmt = (Statement)conn.createStatement();
	        rs 	 = stmt.executeQuery(pQuery);
	     	
	    } catch (SQLException e)
		{
			e.printStackTrace();
		}
	    
		return rs;
	}
	
	public ResultSet getDBRecordsProc(String pQuery)
	{	
		CallableStatement stmt  = null; 
		
		try
	    {
	    	conn = DriverManager.getConnection("hostname", "admin", "admin123");	        
	        stmt = conn.prepareCall(pQuery);	        
	        stmt.registerOutParameter(1, OracleTypes.CURSOR);
	        stmt.execute();
	        rs = (ResultSet) stmt.getObject(1);
	    } catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		return rs;
	}
	
	public void closeConnection()
	{
		if (rs  != null) try { rs.close();  } catch (SQLException ignore) {}
        if (stmt  != null) try { stmt.close();  } catch (SQLException ignore) {}
        if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
	}
}

Package creation in Oracle is a TWO step Process.
1.Declaration of Package
2.Definition of Package

Declaration of Package

  CREATE OR REPLACE PACKAGE TEST IS
    PROCEDURE JUNITPROC(C OUT SYS_REFCURSOR);
  END TEST;

Definition of Package

  CREATE OR REPLACE PACKAGE BODY TEST IS
  PROCEDURE JUNITPROC(C OUT SYS_REFCURSOR) IS
  BEGIN  
    OPEN C FOR
      SELECT 78985450.1245487986418648 DECIMAL_VAL FROM DUAL;
  END JUNITPROC;
END TEST;

There are two types of objects in Hibernate
1. Value Object
2. Entities

Value Objects are the objects which can not stand alone. Take Address, for example. If you say address, people will ask whose address is this. So it can not stand alone.
Entity Objects are those who can stand alone like College and Student.

So in case of value objects preferred way is to Embed them into an entity object. In the example below Address class does not derive the meaning of its own. So Address is Value Object and is Embeddable. Whereas UserDetails(Entities) could stand on its own and it could have Embedded Objects

Address.java

 import javax.persistence.Embeddable;

@Embeddable
public class Address {
	private String Street;
	private String Location;
	private String City;
	
	public String getStreet() {
		return Street;
	}
	public void setStreet(String street) {
		Street = street;
	}
	public String getLocation() {
		return Location;
	}
	public void setLocation(String location) {
		Location = location;
	}
	public String getCity() {
		return City;
	}
	public void setCity(String city) {
		City = city;
	}
}

UserDetails.java

public class UserDetails 
{
 @Embedded
 private Address address;
 .
 .
 .
}

The above code explains how the Embedded and Embeddable annotations can be used in the code.

CreateUser.java

  Address objAddress = new Address();
  objUserDetail.setAddress(objAddress);

Attribute Override

@Embedded
@AttributeOverride (name="Street",column=@Column(name="HOME_STREET"))
private Address addr;

Multiple Attribute Overrides

@Embedded
 @AttributeOverrides({
	@AttributeOverride(name="doorNo", column=@Column(name="Office_DoorNo")),
	@AttributeOverride(name="streetName", column=@Column(name="Office_streetName")),
	@AttributeOverride(name="location", column=@Column(name="Office_location")),
	@AttributeOverride(name="pincode", column=@Column(name="Office_pincode"))
})
private Address addr;
  @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).

modcount of the list lets you know if there has been a structural modification made that might cause the current operation to give incorrect results.

  List<String> arrNames = new ArrayList<String>();
  arrNames.add("Mugil");
  arrNames.add("Vinu");
  arrNames.add("Bala");
  arrNames.add("Madhu");		
  arrNames.remove(0);		
  arrNames.add("Swathi");		
  arrNames.remove(1);

When the control reaches
Line 6 The Size and Modcount of the arrNames would be 4
Line 7 The Size and Modcount would be 5 and size would be 3
Line 7 The Size and Modcount would be 6 and size would be 4

Fine the Screenshots below for further Details

Importing a Java Method in to JSP Page

package com.mugil.servlet;

public class Sample1 
{
  static int pincode = 600018;
  
  public String toString()
  {	
    return "600018";
  }
}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import = "com.mugil.servlet.Sample1"%>    
 <body>
   <%=new Sample1()%>
 </body>

Note:
The following Code wont work

  <%=new Sample1();%>
  <% =new Sample1()%>