Reading constant from properties file
constant.properties

PointA.PointX=-20
PointA.PointY=0

spring.xml

<beans>
	<bean id="pointA" class="com.mugil.shapes.Point">
		<property name="x" value="${PointA.PointX}"/>
		<property name="y" value="${PointA.PointY}"/>
	</bean>
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="constant.properties"></property>
	</bean>
</beans>

Using Interface
spring.xml

<beans>
	<bean id="pointA" class="com.mugil.shapes.Point">
		<property name="x" value="${PointA.PointX}"/>
		<property name="y" value="${PointA.PointY}"/>
	</bean>
	<bean class="com.mugil.shapes.Circle" id="circleId">
		<property name="center" ref="pointA"/>
	</bean>
</beans>

shape.java

public interface Shape { 
	public void drawShape();
}

triangle.java

public class Triangle implements Shape
{
 public void drawShape()
 {
   System.out.println("Shape of Triangle");
 }
}

circle.java

public class Circle implements Shape{
	private Point center;
	
	@Override
	public void drawShape() {
		System.out.println("Shape of Circle ");
		System.out.println("Center of Cirlce "+ getCenter().getX() + " - " + getCenter().getY());
	}

	public Point getCenter() {
		return center;
	}

	public void setCenter(Point center) {
		this.center = center;
	}		
}

The objShape will call the draw method based on the instance referenced at runtime
shape.java

public class DrawingApp {
	public static void main(String[] args)  {
		 ApplicationContext objContext = new ClassPathXmlApplicationContext("spring1.xml");
		Shape objShape =  (Shape)objContext.getBean("circleId");
		objShape.drawShape();
	}
}

ApplicationContextAware and BeanNameAware

  1. The Aware interface has the feel of the listener, callback, or observer design patterns.
  2. Aware interface, which is a super interface to the two.The xxxAware interface is a common pattern used within the Spring framework.
  3. They are typically used to allow a Spring managed bean to be given an object (via the interfaces setXxx method) at Spring bootstrap time.During bootstrapping, Spring will examine each bean to determine if it implements any of the xxxAware interfaces. When one is found, it invokes the interface method, providing the piece of information that is being asked for.

In Spring Bean Lifecycle from creation to Destruction is managed by Spring Container. There may be scenarios where we would want to access bean created by spring container from non spring managed class. The beans created by spring container is available in ApplicationContext. Whenever there are any changes to the bean it would be updated in applicationcontext.
By implementing ApplicationContextAware in the bean which should be accessed outside and calling the setApplicationContext when new ClassPathXmlApplicationContext is called from outside class we can have access to bean from context.

SpringBeans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="helloBean" class="com.mkyong.core.HelloWorld">
		<property name="name" value="Mugil" />
	</bean>
</beans>

HelloWorld.java – Spring Bean

public class HelloWorld implements ApplicationContextAware
{
 private String name;
 private ApplicationContext objContext = null;


 public void setName(String name) {
  this.name = name;
 }

 public void printHello() {
  System.out.println("Spring 3 : Hello ! " + name);
 }

 public void setApplicationContext(ApplicationContext arg0) throws BeansException {
  this.objContext = arg0;
  System.out.println("Called when Object to new ClassPathXmlApplicationContext('springbeans.xml') is created");
 }
}

App.java

public class App 
{
 public static void main(String[] args) 
 {
  ApplicationContext context = new ClassPathXmlApplicationContext("SpringBeans.xml");

  HelloWorld obj = (HelloWorld) context.getBean("helloBean");
  obj.printHello();
 }
}

Output

Called when Object to new ClassPathXmlApplicationContext('springbeans.xml') is created
Spring 3 : Hello ! Mugil

When spring instantiates beans, it looks for a couple of interfaces like ApplicationContextAware and InitializingBean. If they are found, the methods are invoked.

Class<?> beanClass = beanDefinition.getClass();
Object bean = beanClass.newInstance();
if (bean instanceof ApplicationContextAware) 
{
    ((ApplicationContextAware) bean).setApplicationContext(ctx);
}

In newer version it may be better to use annotations, rather than implementing spring-specific interfaces

@Inject // or @Autowired
private ApplicationContext ctx

When BeanPostProcessor implement Object to execute the postProcessBeforeInitialization method,for example ApplicationContextAwareProcessor that added before.

private void invokeAwareInterfaces(Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof EnvironmentAware) {
                ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
            }
            if (bean instanceof EmbeddedValueResolverAware) {
                ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
                        new EmbeddedValueResolver(this.applicationContext.getBeanFactory()));
            }
            if (bean instanceof ResourceLoaderAware) {
                ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
            }
            if (bean instanceof ApplicationEventPublisherAware) {
                ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
            }
            if (bean instanceof MessageSourceAware) {
                ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
            }
            if (bean instanceof ApplicationContextAware) {
                ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
            }
        }
    }

When it is Invoked
Shape.java

//Application System out would be Printed
ApplicationContext objContext = new ClassPathXmlApplicationContext("spring1.xml");

//this.strTriangle would be printed
BeanFactory  objBeanFactory = new XmlBeanFactory(new FileSystemResource("spring.xml"));
Triangle objTriangle2 =  (Triangle)objBeanFactory.getBean("triangleName");

BeanFactoryAware
BeanFactory is used for BeanFactoryAware whereas ApplicationContextAware is used for ApplicationContext.Note that the ApplicationContext interface is a subclass of BeanFactory, and provides additional methods on top of the basic BeanFactory interface.

BeanNameAware Interface
Bean implementing this interface can get its name defined in the Spring container
One possible area of use could be if your building on/ extending the spring framework and would like to acquire the bean name for logging purposes/wiring them etc.

MyBeanName.java

public class MyBeanName implements BeanNameAware 
{
 @Override
 public void setBeanName(String beanName) 
 {
  System.out.println(beanName);
 }
}

Config.java

@Configuration
public class Config 
{ 
    @Bean(name = "myCustomBeanName")
    public MyBeanName getMyBeanName() {
        return new MyBeanName();
    }
}
myCustomBeanName
  1. beanName property represents the bean id registered in the Spring container.When a new bean is given a name in the spring container and if you want to access the name then BeanNameAware should be used
  2. In the above example when the code is run it outputs myCustomBeanName which is the name offered to bean by container at runtime.
  3. If no name is given its going to print name of the method – getMyBeanName as bean name

If you require access to the additional features available on an ApplicationContext? If so, then you should of course use ApplicationContextAware. If not, BeanFactoryAware will be sufficient.Amongst many other things, an ApplicationContext has additional methods for inspecting the beans e.g. containsBeanDefinition, getBeanDefinitionCount, getBeanDefinitionNames, getBeanNamesForType, getBeansOfType that may be useful to you and which are not available on BeanFactory

we should avoid using any of the Aware interfaces, unless we need them. Implementing these interfaces will couple the code to the Spring framework.

————————————————————————————————————————————————————

Inheriting Bean Definition
spring.xml

<beans>
	<bean id="parentTriangle" class="com.mugil.shapes.Triangle">
		<property name="pointA">
			<ref bean="pointA"/>
		</property>
	</bean>
	<bean id="triangleId" class="com.mugil.shapes.Triangle" parent="parentTriangle">
		<property name="pointB" ref="pointB"/>
		<property name="pointC" ref="pointC"/>
	</bean>
<beans>

Above the bean parentTriangle is inherited by the child bean triangleId

spring.xml
Bean definition can also be made as abstract by using abstract=”true” like one below

<beans>
	<bean id="parentTriangle" class="com.mugil.shapes.Triangle" abstract="true">
		<property name="pointA">
			<ref bean="pointA"/>
		</property>
	</bean>
</beans>

Managing Lifecycle of Bean

  1. Note the object for Context objContext is referred using AbstractApplicationContext not ApplicationContext
  2. registerShutdownHook() registers a hook which gets called at the end of application for cleanup

Shape.java

 AbstractApplicationContext objContext = new ClassPathXmlApplicationContext("spring1.xml");
 objContext.registerShutdownHook();

Triangle.java

public class Triangle implements InitializingBean, DisposableBean 
{
 @Override
 public void destroy() throws Exception {
   System.out.println("DisposableBean Called");
 }

 @Override
 public void afterPropertiesSet() throws Exception {
   System.out.println("InitializingBean Called");
 }
}

We can all initialize the methods which should be called for initialization in spring.xml as below
spring.xml

<bean id="triangleId" class="com.mugil.shapes.Triangle" init-method="myInit" destroy-method="myDestroy">
                <property name="pointA" ref="pointA"/>
		<property name="pointB" ref="pointB"/>
		<property name="pointC" ref="pointC"/>
	</bean>

Triangle.java

public class Triangle implements InitializingBean, DisposableBean 
{
  public void myInit()
  {
    System.out.println("Custom Init Method");
  }
	
  public void myDestroy()
  {
    System.out.println("Custom Destroy Method");
  }
}

Priority of method call when it is defined by using XML and Interface implementation

  1. Init method of XML will be called
  2. Custom Init method of Interface will be called
  3. Destroy method of XML will be called
  4. Custom Destroy method of Interface will be called

Bean Post Processor

  1. Will work before and after bean initialization
  2. Works only when called using application initialization of bean. Does not work with setter initialization
  3. called for every initialization of parent and child bean in class

Bean Post Processor

<beans>
	<bean id="triangleId" class="com.mugil.shapes.Triangle">
	    <property name="pointA" ref="pointA"/>
		<property name="pointB" ref="pointB"/>
		<property name="pointC" ref="pointC"/>
	</bean>
	
	<bean id="pointA" class="com.mugil.shapes.Point">
		<property name="x" value="-20"/>
		<property name="y" value="0"/>
	</bean>
	<bean id="pointB" class="com.mugil.shapes.Point">
		<property name="x" value="0"/>
		<property name="y" value="0"/>
	</bean>
	<bean id="pointC" class="com.mugil.shapes.Point">
		<property name="x" value="20"/>
		<property name="y" value="0"/>
	</bean>
	
	<bean class="com.mugil.shapes.BeanInitialization"/>
	
</beans>

BeanInitialization.java

public class BeanInitialization implements BeanPostProcessor
{
	@Override
	public Object postProcessAfterInitialization(Object obj, String objName) throws BeansException 
       {
	  System.out.println("After Initialization of " + objName);
	  return obj;
	}

	@Override
	public Object postProcessBeforeInitialization(Object obj, String objName) throws BeansException 
       {
	  System.out.println("Before Initialization of " + objName);
	  return obj;
	}

}

So the above code runs four times for bean initialization of pointA,pointB,pointC and Triangle

shape.java

public class Shape 
{ 
  public static void main(String[] args)  
  {
    ApplicationContext objContext = new ClassPathXmlApplicationContext("spring1.xml");
    Triangle objTriangle2 =  (Triangle)objContext.getBean("triangleId");
    . 
    .
    .
}

BeanFactoryPostProcessor initialization happens before the beans gets initialized in the bean factory.

BeanInitialization2.java

public class BeanInitialization2 implements BeanFactoryPostProcessor
{
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException 
  {
     System.out.println("This is Bean factory Post Processor");
  }
}

spring.xml

<beans>
  <bean class="com.mugil.shapes.BeanInitialization2"/>	
</beans>

spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="triangleId" class="com.mugil.shapes.Triangle"/>
</beans>

Triangle.java

package com.mugil.shapes;

public class Triangle {
	private String type;
	
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public void drawShape()
	{
		System.out.println("Shape of Triangle");
	}
}

Reading value of Bean by Application Context and Bean Factory

public class Shape 
{
   public static void main(String[] args) 
   {
	ApplicationContext objContext = new ClassPathXmlApplicationContext("spring1.xml");
	Triangle objTriangle1 =  (Triangle)objContext.getBean("triangleId");
	objTriangle1.drawShape();
		
		
	BeanFactory  objBeanFactory = new XmlBeanFactory(new FileSystemResource("spring.xml"));
	Triangle objTriangle2 =  (Triangle)objBeanFactory.getBean("triangleId");
	objTriangle2.drawShape();
    }
}

Constructor Initialization
Triangle.java

package com.mugil.shapes;

public class Triangle 
{
	private String type;

        public Triangle(String ptype)
	{
		this.type = ptype;
	}
	
        public void drawShape()
	{
		System.out.println("Shape of Triangle");
	}
}

The Index Specifies which variable in the Bean is Initialized

<beans>
	<bean id="triangleId" class="com.mugil.shapes.Triangle">
		<constructor-arg index="0" value="Isolseles"/>
	</bean>
</beans>

Real World Dependency Injection
spring.xml

 
<beans>
	<bean id="triangleId" class="com.mugil.shapes.Triangle">
		<property name="pointA" ref="point1"/>
		<property name="pointB" ref="point2"/>
		<property name="pointC" ref="point3"/>
	</bean>
	
	<bean id="point1" class="com.mugil.shapes.Point">
		<property name="x" value="-20"/>
		<property name="y" value="0"/>
	</bean>
	<bean id="point2" class="com.mugil.shapes.Point">
		<property name="x" value="0"/>
		<property name="y" value="0"/>
	</bean>
	<bean id="point3" class="com.mugil.shapes.Point">
		<property name="x" value="20"/>
		<property name="y" value="0"/>
	</bean>
	
</beans>

Triangle.java

 
public class Triangle {
	private String type;
	private Point pointA;
	private Point pointB;
	private Point pointC;
	
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public void drawShape()
	{
		System.out.println("Shape of Triangle");
	}

	public Point getPointA() {
		return pointA;
	}

	public void setPointA(Point pointA) {
		this.pointA = pointA;
	}

	public Point getPointB() {
		return pointB;
	}

	public void setPointB(Point pointB) {
		this.pointB = pointB;
	}

	public Point getPointC() {
		return pointC;
	}

	public void setPointC(Point pointC) {
		this.pointC = pointC;
	}
}

Point.java

 
package com.mugil.shapes;

public class Point {
	private int x;
	private int y;
	
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
}

Shape.java

 
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;

public class Shape 
{
    public static void main(String[] args) 
    {		
	BeanFactory  objBeanFactory = new XmlBeanFactory(new FileSystemResource("spring.xml"));
	Triangle objTriangle2 =  (Triangle)objBeanFactory.getBean("triangleId");
		
	System.out.println("The Refereeed Points are = ");
	System.out.println("Point A :" + objTriangle2.getPointA().getX() +" " + objTriangle2.getPointA().getY());
	System.out.println("Point B :" + objTriangle2.getPointB().getX() +" " + objTriangle2.getPointB().getY());
	System.out.println("Point C :" + objTriangle2.getPointC().getX() +" " + objTriangle2.getPointC().getY());		
	}
}

Incase the value of the bean wont be referred else where you can define the bean property simple as below

<beans>
	<bean id="triangleId" class="com.mugil.shapes.Triangle">
		<property name="pointA">
			<bean id="point1" class="com.mugil.shapes.Point">
				<property name="x" value="-20"/>
				<property name="y" value="0"/>
			</bean>			
		</property>
		<property name="pointB" ref="point2"/>
		<property name="pointC" ref="point3"/>
	</bean>

instead of

<beans>
	<bean id="triangleId" class="com.mugil.shapes.Triangle">
		<property name="pointA" ref="point1"/>
		<property name="pointB" ref="point2"/>
		<property name="pointC" ref="point3"/>
	</bean>
	
	<bean id="point1" class="com.mugil.shapes.Point">
		<property name="x" value="-20"/>
		<property name="y" value="0"/>
	</bean>
.
.
.

Using Alias

<bean id="triangleId" class="com.mugil.shapes.Triangle" name="triangleName">
.
.
.
</bean>
<alias name="triangleId" alias="triangle-alias"/>

In Java we can refer either by name or by alias as below
Using Alias

.
.
Triangle objTriangle2 =  (Triangle)objBeanFactory.getBean("triangleName");
(or)
Triangle objTriangle2 =  (Triangle)objBeanFactory.getBean("triangle-alias");
.
.

Using List
Triangle.java

public class Triangle 
{
    private List<Point> points;	
	
    public List<Point> getPoints() 
    {
	return points;
    }

    public void setPoints(List<Point> points) 
    {
 	this.points = points;
    }			
}

spring.xml

<beans>
	<bean id="triangleId" class="com.mugil.shapes.Triangle" name="triangleName">
		<property name="points">
			<list>
				<ref bean="point1"/>
				<ref bean="point2"/>
				<ref bean="point3"/>
			</list>		
		</property>		
	</bean>
	<bean id="point1" class="com.mugil.shapes.Point">
			<property name="x" value="-20"/>
			<property name="y" value="0"/>
	</bean>
	<bean id="point2" class="com.mugil.shapes.Point">
		<property name="x" value="0"/>
		<property name="y" value="0"/>
	</bean>
	<bean id="point3" class="com.mugil.shapes.Point">
		<property name="x" value="20"/>
		<property name="y" value="0"/>
	</bean>
</beans>

Shape.java

List<Point> arrPoints = objTriangle2.getPoints();
		
 for (Point objPoint : arrPoints) 
 {
   System.out.println("Point :" + objPoint.getX() +" " + objPoint.getY());
 }

Autowiring
Autowiring can be done based on name as below, byType and byConstructor.

<bean id="triangleId" class="com.mugil.shapes.Triangle" name="triangleName" autowire="byName">	
</bean>
<bean id="pointA" class="com.mugil.shapes.Point">
  <property name="x" value="-20"/>
  <property name="y" value="0"/>
</bean>
<bean id="pointB" class="com.mugil.shapes.Point">
  <property name="x" value="0"/>
  <property name="y" value="0"/>
</bean>
<bean id="pointC" class="com.mugil.shapes.Point">
  <property name="x" value="20"/>
  <property name="y" value="0"/>
</bean>

The Name of the instanceVariable in class should match the autowired xml bean Name.
Triangle.java

 
public class Triangle {	
	private Point pointA;
	private Point pointB;
	private Point pointC;
.        
.
}

Bubble Sort

public void bubbleSort()
{
	for (int i = arrNumbers.length-1; i>1 ; i--) 
	{	
		for (int j = 0; j < i; j++) 
		{			
			if(arrNumbers[j] > arrNumbers[j+1])
			{
				swapValuesAtIndex(j, j+1);					
			}
			
			/*IterationDisplay(arrNumbers, j);*/
		}
	}
}

Selection Sort
Selection sort works by dividing the list into 2 Parts. Sorted and Unsorted.Taking one element at a time as Minimum element it works by comparing the minimum element with other elements in the list.

public void selectionSort()
{
	int minElement = 0;
	
	for (int i = 0; i< arrNumbers.length ; i++) 
	{
     	minElement = i;
		
		for (int j = i; j < arrNumbers.length; j++) 
		{			
			if(arrNumbers[minElement] > arrNumbers[j])
			{						
				minElement =  j;
			}
		}
		
		swapValuesAtIndex(minElement, i);
	}
}

Insertion Sort
Insertion sort is the best sorting method compared to others.The list is divided into sorted and unsorted portion. Once a no is selected for comparison it will not ened without placing the no at the correct location.

public void insertionSort()
{	
	for (int i = 1; i < arrNumbers.length; i++) 
	{
		int j = i;
		int toCompare = arrNumbers[i];
		
		//holds no to Insert - arrNumbers[j-1]
		while((j>0) && (arrNumbers[j-1] > toCompare))
		{
			arrNumbers[j] = arrNumbers[j-1];
			j--;
		}
		
		arrNumbers[j] =  toCompare;		
	}
}
public static String[] removeElements(String[] input, String deleteMe) 
{
    List result = new LinkedList();

    for(String item : input)
        if(!deleteMe.equals(item))
            result.add(item);

    return result.toArray(input);
}

CreationScript.java

	sessionFactory = createSessionFactory();
	Session objSession = sessionFactory.openSession();
	objSession.beginTransaction();

	Criteria crt = objSession.createCriteria(Users.class);
	crt.add(Restrictions.eq("UserName", "UserName 9"));


	List<Users> arrUsers = (List<Users>)crt.list();

	for (Users users : arrUsers) {
		System.out.println(users.getUserName());
	}

AND Restrictions

Criteria crt = objSession.createCriteria(Users.class);
	crt.add(Restrictions.eq("UserName", "UserName 9")).
		add(Restrictions.gt("UserId", 5));
Criteria crt = objSession.createCriteria(Users.class);
	crt.add(Restrictions.eq("UserName", "UserName 9")).
		add(Restrictions.gt("UserId", 5));
Criteria crt = objSession.createCriteria(Users.class);
		crt.add(Restrictions.eq("UserName", "UserName 9")).
			add(Restrictions.between("UserId", 5, 10));
Criteria crt = objSession.createCriteria(Users.class);
		crt.add(Restrictions.eq("UserName", "UserName 9")).
			add(Restrictions.between("UserId", 5, 10));

OR Restrictions

Criteria crt = objSession.createCriteria(Users.class);
		crt.add(Restrictions.or(Restrictions.between("UserId", 0, 5), Restrictions.like("UserName", "Updated %")));

Getting list of Users from users Table

     sessionFactory = createSessionFactory();
     Session objSession = sessionFactory.openSession();
     objSession.beginTransaction();
		
     Query objQuery = objSession.createQuery("from Users");
     List<Users> arrUsers = objQuery.list();
		
     objSession.getTransaction().commit();
     objSession.close();
		
     System.out.println(arrUsers.size());

     for (Users users : arrUsers) {
	System.out.println(users.getUserName());
     }

Pagination Using HQL

    Query objQuery = objSession.createQuery("from Users");		
    objQuery.setFirstResult(5);
    objQuery.setMaxResults(2);
    List<Users> arrUsers = objQuery.list();
				
    objSession.getTransaction().commit();
    objSession.close();
		
    System.out.println(arrUsers.size());
		
    for (Users users : arrUsers) {
	System.out.println(users.getUserName());
    }

Note: In Pagination the Starting record is specified by setFirstResult and ending record is specified by setMaxResults.

Taking a Specific Column for Entity

	Query objQuery = objSession.createQuery("select UserName from Users");		
	objQuery.setFirstResult(5);
	objQuery.setMaxResults(2);
	List<String> arrUsers = (List<String>)objQuery.list();

	objSession.getTransaction().commit();
	objSession.close();

	System.out.println(arrUsers.size());

	for (String users : arrUsers) {
		System.out.println(users);
	}

Note :
The Object Name in entity should be same as specified in class including Case. username will not work in select query but UserName does.

Parameter Binding in Hibernate
Method 1

  Query objQuery = objSession.createQuery("from Users where UserId >?");
  objQuery.setParameter(0, 5);		
  List<Users> arrUsers = (List<Users>)objQuery.list();

  for (Users users : arrUsers) {
	System.out.println(users.getUserName());
  }

Method 2

     Query objQuery = objSession.createQuery("from Users where UserId > :limit");
     objQuery.setInteger("limit", 5);
		
     List<Users> arrUsers = (List<Users>)objQuery.list();
				
     objSession.getTransaction().commit();
     objSession.close();
	
     for (Users users : arrUsers) {
	System.out.println(users.getUserName());
     }

NamedQuery vs NamedNativeQuery
NamedQuery helps to consolidate all query at particular place.

users.java

@Entity
@NamedQuery(name="Users.byUserId", query="from Users where UserId=?")
public class Users {
	@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
	private int UserId;
	private String UserName;
	
	public int getUserId() {
		return UserId;
	}
	public void setUserId(int userId) {
		UserId = userId;
	}
	public String getUserName() {
		return UserName;
	}
	public void setUserName(String userName) {
		UserName = userName;
	}	
}

CreationScript.java

	sessionFactory = createSessionFactory();
	Session objSession = sessionFactory.openSession();
	objSession.beginTransaction();
		
	Query objQuery = objSession.getNamedQuery("Users.byUserId");
        objQuery.setInteger(0, 5);
		
	List<Users> arrUsers = (List<Users>)objQuery.list();
	
	for (Users users : arrUsers) {
	   System.out.println(users.getUserName());
	}

NativeQueries helps us to query the table directly by using table name instead of querying through Entity like one in NamedQuery.This is useful when we use stored procedure to take our resultSets.

users.java

@Entity
@NamedNativeQuery(name="Users.byUserId", query="SELECT * from Users where UserId=?", resultClass=Users.class)
public class Users {
	@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
	private int UserId;
	private String UserName;
	
	public int getUserId() {
		return UserId;
	}
	public void setUserId(int userId) {
		UserId = userId;
	}
	public String getUserName() {
		return UserName;
	}
	public void setUserName(String userName) {
		UserName = userName;
	}	
} 

Note: resultClass=Users.class should be specified or else object class cast exception would be thrown.

There may be times where you want to retrieve data from DB, do some changes in it and save back the data.In such a time the connection could not be kept open for the whole period of time since db connections are resource intensive.

So I will fetch the object -> close the Session -> Do some operations -> Open new session again -> Update the Object -> Close the Session.

	sessionFactory = createSessionFactory();
	Session objSession = sessionFactory.openSession();
	objSession.beginTransaction();		
	Users objUser = objSession.get(com.mugil.user.Users.class, 11);
	objSession.getTransaction().commit();
	objSession.close();

	objUser.setUserName("Updated");

	objSession = sessionFactory.openSession();
	objSession.beginTransaction();
	objSession.update(objUser);
	objSession.getTransaction().commit();
	objSession.close();

Now the way Hibernate works is it first runs the select query for the value which should be changed and updates the value.So 2 queries for the whole process.Now there are chance’s the value fetched from DB may or may not be changed.So we can do a check which checks the fetched and updated value for uniquess before running the update query.If the fetched data is not changed th update query wont be run.

The Annotation for that is as below.

 @Entity
 @org.hibernate.annotations.Entity(selectBeforeUpdate=true)

 	objSession.beginTransaction();		
	Users objUser = new Users();
	objUser.setUserName("Max");
	.
	.
	.
	----Transient State----
	.
	.		
	objSession.save(objUser);
	.
	.
	.
	----Persistent State----
	.
	.		
	objUser.setUserName("Max Muller");
	.
	.
	.
	----Persistent State----
	.
	.
	objSession.getTransaction().commit();
	objSession.close();
	.
	.
	.
	----Detached State----
	.
	.
	//Doesnot get reflected
	objUser.setUserName("Max Muller");
	.
	.
  • The object will be in Transient State until it is saved.An object is in transient state if it just has been instantiated using the new operator and there is no reference of it in the database i.e it does not represent any row in the database.
  • The object will be in Persistent State until the session is closed.An object is in the persistent state if it has some reference in the database i.e it represent some row in the database and identifier value is assigned to it. If any changes are made to the object then hibernate will detect those changes and effects will be there in the database that is why the name Persistent. These changes are made when session is closed. A persistent object is in the session scope.
  • The object will be in Detached State once the session is closed.An object that has been persistent and is no longer in the session scope. The hibernate will not detect any changes made to this object. It can be connected to the session again to make it persistent again.

The changes done after the session close will not get reflected

Image Showing Values in Table with and Without DiscriminatorColumn defined

  • By Default Hibernate follows Single Table Inheritance
  • DiscriminatorColumn tells hibernate the name in which DiscriminatorColumn should be save or else it would be saved as DType
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="VEHICLE_TYPE",
		     discriminatorType=DiscriminatorType.STRING)

Vehicles.java

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="VEHICLE_TYPE",
		     discriminatorType=DiscriminatorType.STRING)
public class Vehicles {
	@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
	private int VehicleId;	
	private String name;
		
	public int getVehicleId() {
		return VehicleId;
	}
	public void setVehicleId(int vehicleId) {
		VehicleId = vehicleId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
}

TwoWheelers.java

@Entity
@DiscriminatorValue("Bike")
public class TwoWheelers extends Vehicles{
	private String steeringHolder;

	public String getSteeringHolder() {
		return steeringHolder;
	}

	public void setSteeringHolder(String steeringHolder) {
		this.steeringHolder = steeringHolder;
	}
}

FourWheelers.java

@Entity
@DiscriminatorValue("Car")
public class FourWheelers extends Vehicles{
	
	private String steeringWheel;

	public String getSteeringWheel() {
		return steeringWheel;
	}

	public void setSteeringWheel(String steeringWheel) {
		this.steeringWheel = steeringWheel;
	}
	
}

By Using the below annotation individual tables would be created for all the subclasses instead of placing all the values getting placed in a single class.

InheritanceType.TABLE_PER_CLASS

@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

InheritanceType.JOINED

@Inheritance(strategy=InheritanceType.JOINED)

Using InheritanceType.JOINED gets more normalized table compared to InheritanceType.TABLE_PER_CLASS