How To Synchronize ArrayList In Java with Example


In This Tutorial we will see How To Get Synchronized ArrayList In Java with Example

In java.util.Collections class We have one method called synchronizedList().This Method returns the synchronized Arraylist in java.

By Using This Method public static List synchronizedList(List list) we can perform the synchronization on ArrayList.

Method Declaration:


public static List synchronizedList(List list)

This Method Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list. It is imperative that the user manually synchronize on the returned list when iterating over it.

Here one important point to be noted is when we iterate synchronized arraylist we need to must use synchronized block. like following.

 List list = Collections.synchronizedList(new ArrayList());
      ...
  synchronized (list) {
      Iterator i = list.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }

Now Let's See One Example On How TO get synchronized ArrayList In Java.

Example


package com.javalchool.practice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class SynchronizedArrayListDemo {

 
 public static void main(String[] args) {
  
  ArrayList<String>  arraylist = new ArrayList<String>();
  
  arraylist.add("AAA");
  arraylist.add("BBB");
  arraylist.add("CCC");
  arraylist.add("DDD");
  
  // displaying arraylist data which is non-synchronized
  System.out.println("Non-synchronized ArrayList"+arraylist);
  
  
  List  list1 = Collections.synchronizedList(arraylist);
  
  System.out.println(list1);
  
   
   synchronized (list1) {
       Iterator i = list1.iterator(); // Must be in synchronized block
       while (i.hasNext())
           System.out.println(i.next());
   }

 }

}

output:


Non-synchronized ArrayList[AAA, BBB, CCC, DDD]
[AAA, BBB, CCC, DDD]
AAA
BBB
CCC
DDD

ArrayList Clone With Example in java


In This Tutorial we will See How To clone One ArrayList To Another ArrayList.

In Java.util.ArrayList Class We have One Method called clone().

By Using java.util.ArrayList.clone() method we can perform ArrayList Clone operation.

Method Declaration:


public Object clone()

This Method Returns a shallow copy of this ArrayList instance.

Example



package com.javalchool.practice;

import java.util.ArrayList;

public class ArrayListCloneDemo {

 
 public static void main(String[] args) {
    ArrayList<String>  arraylist = new ArrayList<String>();
    
   arraylist.add("AAA");
   arraylist.add("BBB");
   arraylist.add("CCC");
   
   System.out.println("arraylist before cloning"+arraylist);
   
   
   
   // Here We are calling clone method on arraylist 
 
   ArrayList<String> arraylistclone = (ArrayList<String>)arraylist.clone();
   
   System.out.println("cloned arraylist"+arraylistclone);
   
   arraylist.remove(1);
   arraylist.add("Bala");
   
   arraylist.addAll(arraylist);
   
   System.out.println("arraylist before clone"+arraylist);
   
   System.out.println("arraylist cloned "+arraylistclone);
   
   

 }

}


output:


arraylist before cloning[AAA, BBB, CCC]
cloned arraylist[AAA, BBB, CCC]
arraylist before clone[AAA, CCC, Bala, AAA, CCC, Bala]
arraylist cloned [AAA, BBB, CCC]


Java ArrayList


The java.util.ArrayList class is one of the most commonly used of all the classes in the Collections Framework.

ArrayList is Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

Some Imortanat points about ArrayList:


  • It can grow dynamically.
  • It provides more powerful insertion and search mechanisms than arrays.
  • It Contains dulicate elements.
  • ArrayList Cares about Index.So ArrayList Provides Insertion order of elements.
  • It contains null values also.
  • It implements Serializable,clonable,Random access Interfaces.
  • It Provides Fast Iteration.
  • ArrayList is Non Synchronized.
  • ArrayList class Methods


    public boolean add(E o)

    This Method Will Appends the specified element to the end of this list.

    arraylist.add("BBB");
    

    public void add(int index, E element)

    This Method Will Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

    arraylist.add(2,"AA");
    
    in above line will add the "AA" element to the arraylist 2nd position.

    public E remove(int index)

    This Method will Removes the element at the specified position in this list.

    arraylist.remove(3);
    
    above line will removes the arraylist element at 3rd position.

    public boolean addAll(Collection c)

    This method will Appends all of the elements in the specified Collection to the end of this list, in the order that they are returned by the specified Collection's Iterator. The behavior of this operation is undefined if the specified Collection is modified while the operation is in progress.

    arraylist.add(arraylist);
    
    

    public void clear()

    This Method will Removes all of the elements from this list. The list will be empty after this call returns.

    arraylist.clear();
    

    public E get(int index)

    This Method Returns the element at the specified position in this list.

    arraylist.get(2);
    
    above line returns the element at arraylist 2nd position.

    public E set(int index, E element)

    This Method Replaces the element at the specified position in this list with the specified element.

    arraylist.set(2,"bbb");
    
    
    above line will replace the arraylist 2nd position value with "bbb".

    public int size()

    This Method Returns the number of elements in this list.

    arraylist.size();
    
    This Method returns the size of the arraylist.

    Constructors of ArrayList:


    ArrayList arraylist = new ArrayList();

    Constructs an empty list with an initial capacity of ten.

    ArrayList arraylist = new ArrayList(int initial capacity);

    Constructs an empty list with the specified initial capacity.

    ArrayList arraylist = new ArrayList(Collection c);

    Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

    till Now We Have Seen Details about ArrayList,Now We will See One Example On ArrayList.

    Example


    package com.javalchool.practice;
    
    import java.util.ArrayList;
    
    public class ArrayListDemo {
     
     public static  void main(String[] args){
      
      //Creation Of ArrayList Constructor 
      
      ArrayList arraylist = new ArrayList();
      
      //adding elements to the list 
      arraylist.add("AAA");
      arraylist.add("BBB");
      arraylist.add("CCC");
      arraylist.add("DDD");
      //displaying the arraylist elements before adding duplicate elements 
      
      System.out.println("ArrayList Elements " +arraylist);
      //adding duplicate element
      arraylist.add("AAA");
      arraylist.add("BBB");
      //displaying the arraylist elements  after adding duplicate elements 
      System.out.println("ArrayList after Adding The Duplicate elements"+arraylist);
      
      //adding the null values to the arraylist 
      arraylist.add(null);
      
      System.out.println("ArrayList After Adding Null"+arraylist);
      
      //Inserting element specified position in this arraylist
      arraylist.add(2, "GGG");
      System.out.println(arraylist);
      
      //removing the 4th position element in  arraylist
       arraylist.remove(4);
       
       System.out.println("arraylist after removing the 4th positon element"+arraylist);
       
       //adding  all arraylist elements to the arraylist 
       arraylist.addAll(arraylist);
      
       System.out.println(arraylist);
     }
    
    }
    
    
    

    output:


    ArrayList Elements [AAA, BBB, CCC, DDD]
    ArrayList after Adding The Duplicate elements[AAA, BBB, CCC, DDD, AAA, BBB]
    ArrayList After Adding Null[AAA, BBB, CCC, DDD, AAA, BBB, null]
    [AAA, BBB, GGG, CCC, DDD, AAA, BBB, null]
    arraylist after removing the 4th positon element[AAA, BBB, GGG, CCC, AAA, BBB, null]
    [AAA, BBB, GGG, CCC, AAA, BBB, null, AAA, BBB, GGG, CCC, AAA, BBB, null]
    
    

    what is main method in java?

    In java program jvm always searches for the main() method with the following structure.

    Public static void main(String[] args)

    .

    Public:

    jvm will call this method from anywhere

    Static:

    Without creation of object also jvm has to call this method.

    Void:

    The main does not return anything to jvm.

    Main:

    main is the method name.it is configured in jvm .

    String[] args:

    these are the command line arguments.

    If we are done any changes to the above structure we will compile time error saying : NoSuchMethodError:main.

    1.Main method can be declared as a another modifiers also:

    1.final

    2.Synchronized

    3. strictfp

    Example

      //HelloWorld.java
    final synchronized strictfp public static void main(String[] args)
    {
       System.out.println("helloworld");
    }
    

    OutPut:

    helloworld

    Hibernate One To Many Mapping With Annotation Tutorial With Example


    In Previous Tutorial we have seen Hibernate One TO Many XML Mapping.In This Tutorial We Will Learn Hibernate One To Many Mapping With Annotation.

    Definition:

                "One To Many Mapping occurs when one entity object is related to many objects of another              entity."
    That Means one record of one Table is related to many rows of another Table In Database.
    For Example One Movie is having Many Actors.
    Let Us See An Example For Hibernate One To Many Mapping With Annotation
    Database Table Design
    The Following Diagram is One To Many Table Design.In Database Create Following Two Tables.According Diagram One Movie is having Association on Many Actors.



    /*Create Table movie
    
    CREATE TABLE `movie` (
      `movie_id` int(11) NOT NULL,
      `movie_name` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`movie_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    
     
    /*Create Table actors
    
    CREATE TABLE `actors` (
      `actor_id` int(11) NOT NULL,
      `actor_name` varchar(255) DEFAULT NULL,
      `movie_id` int(11) NOT NULL,
      PRIMARY KEY (`actor_id`),
      KEY `FKAB2F951E6F3463B8` (`movie_id`),
      CONSTRAINT `FKAB2F951E6F3463B8` FOREIGN KEY (`movie_id`) REFERENCES `movie` (`movie_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    
    
    


    Project Structure:























    Maven Dependencies
    File:pom.xml
    pom.xml contains Dependencies For Hibernate And MySql And JPA
    
      4.0.0
      HibernateOneToManyAnnotation
      HibernateOneToManyAnnotation
      0.0.1-SNAPSHOT
      
      
      
     org.hibernate
     hibernate-core
     3.6.7.Final
    
    
    
     mysql
     mysql-connector-java
     5.1.37
    
    
     antlr
     antlr
     2.7.6
    
    
     org.hibernate.javax.persistence
     hibernate-jpa-2.0-api
     1.0.1.Final
    
    
    
     dom4j
     dom4j
     1.6.1
        
         
          xml-apis
          xml-apis
         
        
    
    
     javassist
     javassist
     3.10.0.GA
    
    
    
     commons-collections
     commons-collections
     3.1
    
    
     javax.transaction
     jta
     1.1
    
    
     org.hibernate
     hibernate-commons-annotations
     3.2.0.Final
    
    
     org.slf4j
     slf4j-api
     1.6.1
    
    
    
     commons-logging
     commons-logging
     1.2
    
    
    
    


    Hibernate Model Classes
    File:Movie.java
    package com.javalschool.model;
    
    import java.util.Set;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
    @Entity
    @Table(name = "movie")
    public class Movie {
     @Id
     @Column(name="movie_id", nullable = false)
     private int movieId;
     @Column(name="movie_name")
     private String movieName;
     @OneToMany(targetEntity=Actors.class,cascade=CascadeType.ALL)
     @JoinColumn(name="movie_id", nullable = false)
     private Set actors;
     public int getMovieId() {
      return movieId;
     }
     public void setMovieId(int movieId) {
      this.movieId = movieId;
     }
     public String getMovieName() {
      return movieName;
     }
     public void setMovieName(String movieName) {
      this.movieName = movieName;
     }
     public Set getActors() {
      return actors;
     }
     public void setActors(Set actors) {
      this.actors = actors;
     }
     
    
    }
    
    
    The Following Two Annotations will Represent The One To Many Mapping
    @OneToMany
    @JoinColumn

    File:Actors.java
    package com.javalschool.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "actors")
    public class Actors {
     @Id
     @Column(name = "actor_id")
     private int actorId;
     @Column(name = "actor_name")
     private String actorName;
    
     public int getActorId() {
      return actorId;
     }
    
     public void setActorId(int actorId) {
      this.actorId = actorId;
     }
    
     public String getActorName() {
      return actorName;
     }
    
     public void setActorName(String actorName) {
      this.actorName = actorName;
     }
    
    }
    
    

    Hibernate Configuration File
    File:hibernate.cfg.xml
    &lt?xml version="1.0" encoding="utf-8"?&gt
    &lt!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"&gt
    
    
    
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/mysql
        root
        root123
        org.hibernate.dialect.MySQLDialect
        create
        true
        
        
    
    
    Now Create The Test class And Run The Application
    File:Test.java
    package com.javalschool.test;
    
    import java.util.HashSet;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    
    import com.javalschool.model.Actors;
    
    import com.javalschool.model.Movie;
    
    
    public class Test {
    
     public static void main(String[] args) {
          Configuration configuration = new Configuration();
          configuration.configure();
          SessionFactory sessionFactory = configuration.buildSessionFactory();
          Session session = sessionFactory.openSession();
          Transaction transaction= session.beginTransaction();
          
          Movie movie = new Movie();
          movie.setMovieId(987);
          movie.setMovieName("ABC");
          
          Actors actor = new Actors();
          actor.setActorId(983);
          actor.setActorName("xyz");
          
          Actors actor1 = new Actors();
          actor1.setActorId(389);
          actor1.setActorName("AAA");
          
          
          Actors actor2 = new Actors();
          actor2.setActorId(76);
          actor2.setActorName("BBB");
         
          
          HashSet hashset = new HashSet();
          hashset.add(actor);
          hashset.add(actor1);
          hashset.add(actor2);
          
          movie.setActors(hashset);
          session.save(movie);
          session.save(actor);
          session.save(actor1);
          session.save(actor2);
          transaction.commit();
          session.close();
          sessionFactory.close();
          
          
     }
    
    }
    
    
    output


    Movie Table





    Actors Table

    Hibernate One To Many XML Mapping Tutorial with Example:


    In This Tutorial we will see The One To Many Mapping with XML.
    " One To Many Mapping occurs when one entity instance can have relation with another entity multiple instances."
    For Example each one "Project"can be associated with multiple "Developers".

    Let Us see An Example For Hibernate One To Many XML Mapping
    1.Database  Table Design

    The Following diagram is one-to-many relationship table design.


    Create Database Tables

    create Two tables in database "project" and "developers".
    The Following is MYSql table Script
    //project table
    
    
    CREATE TABLE `project` (
      `projectId` int(11) NOT NULL,
      `projectName` varchar(45) DEFAULT NULL,
      PRIMARY KEY (`projectId`)
    ) ENGINE=InnoDB DEFAULT 
    
    CHARSET=latin1
    
    /*developers table*/
    CREATE TABLE `developers` (
      `developerId` int(11) NOT NULL,
      `developerName` varchar(45) DEFAULT NULL,
      `projectId` int(11) DEFAULT NULL,
      PRIMARY KEY (`developerId`),
      KEY `projectId` (`projectId`),
    CONSTRAINT `projectId` FOREIGN KEY (`projectId`) REFERENCES `project` 
    
    (`projectId`) ON DELETE CASCADE ON UPDATE CASCADE
    ) ENGINE=InnoDB DEFAULT 
    
    CHARSET=latin1
    2.The Project structure


    3.Maven Dependencies
    File:pom.xml
    pom.xml contains dependecies for Hibernate and mysql.
    
      4.0.0
      HibernateExample
      HibernateExample
      0.0.1-SNAPSHOT
      
      
     org.hibernate
     hibernate-core
     3.6.7.Final
    
    
    
     mysql
     mysql-connector-java
     5.1.37
    
    
     antlr
     antlr
     2.7.6
    
    
     org.hibernate.javax.persistence
     hibernate-jpa-2.0-api
     1.0.1.Final
    
    
    
     dom4j
     dom4j
     1.6.1
        
         
          xml-apis
          xml-apis
         
        
    
    
     javassist
     javassist
     3.10.0.GA
    
    
    
     commons-collections
     commons-collections
     3.1
    
    
     javax.transaction
     jta
     1.1
    
    
     org.hibernate
     hibernate-commons-annotations
     3.2.0.Final
    
    
     org.slf4j
     slf4j-api
     1.6.1
    
    
    
     commons-logging
     commons-logging
     1.2
    
    
      
    
    

    4.Hibernate Model classes

    File:Project.java
    package com.javalschool.model;
    
    import java.io.Serializable;
    import java.util.Set;
    
    public class Project implements Serializable {
    
     /**
      *@author Mankali 
      */
     private static final long serialVersionUID = 1L;
     private int projectId;
     private String projectName;
     private Set developers;
     public int getProjectId() {
      return projectId;
     }
     public void setProjectId(int projectId) {
      this.projectId = projectId;
     }
     public String getProjectName() {
      return projectName;
     }
     public void setProjectName(String projectName) {
      this.projectName = projectName;
     }
     public Set getDevelopers() {
      return developers;
     }
     public void setDevelopers(Set developers) {
      this.developers = developers;
     }
     
    
    }
    

    File:Developers.java
    package com.javalschool.model;
    
    import java.io.Serializable;
    
    public class Developers implements Serializable{
    
     /**
      * @author Mankali
      */
     private static final long serialVersionUID = 1L;
     private int developerId;
     private String developerName;
      public int getDeveloperId() {
      return developerId;
     }
     public void setDeveloperId(int developerId) {
      this.developerId = developerId;
     }
      
     public String getDeveloperName() {
      return developerName;
     }
     public void setDeveloperName(String developerName) {
      this.developerName = developerName;
     }
     
     
    
    }
    
    

    5.Hibernate XML Mapping Files

    Now Create Hibernate Mapping Files For Both classes.

    File:project.hbm.xml


    
    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    
     
     
       
      
      
    
      
       
       
      
     
      
    

    File:developers.hbm.xml
      
    <!DOCTYPE hibernate-mapping PUBLIC  
              "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
              "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
    `
     
      
       
      
      
    
     
     
    

    6.Hibernate Configuration File

    File:hibernate.cfg.xml


    
    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    
    
    
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/mysql
        root
        root123
        org.hibernate.dialect.MySQLDialect
        create
        true
        
        
    
    
    
    
    7.Now Create Test class And Run The Application

    File:Test.java
    package com.javalschool.test;
    
    import java.util.HashSet;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    
    import com.javalschool.model.Developers;
    import com.javalschool.model.Project;
    
    public class Test {
    
     @SuppressWarnings({ "rawtypes", "unchecked" })
     public static void main(String[] args) {
          Configuration configuration = new Configuration();
          configuration.configure();
          SessionFactory sessionFactory = configuration.buildSessionFactory();
          Session session = sessionFactory.openSession();
          Transaction transaction= session.beginTransaction();
          
          Project project = new Project();
          project.setProjectId(87687);
          project.setProjectName("xyz");
          
          Developers developers = new Developers();
          developers.setDeveloperId(23453);
          developers.setDeveloperName("AAA");
          
          Developers developers1 = new Developers();
          developers1.setDeveloperId(45323);
          developers1.setDeveloperName("BBB");
          
          Developers developers2 = new Developers();
          developers2.setDeveloperId(23430);
          developers2.setDeveloperName("CCC");
          
          HashSet hashset = new HashSet();
          hashset.add(developers);
          hashset.add(developers1);
          hashset.add(developers2);
          
          project.setDevelopers(hashset);
          session.save(project);
          session.save(developers);
          session.save(developers1);
          session.save(developers2);
          
          transaction.commit();
          session.close();
          sessionFactory.close();
          
          
     }
    
    }
    
    
    Output



    Project Table in Database after applying one to many mapping

    developers Table in Database after applying one to many mapping

    spring dependency checking with @Required Annotation Example


    The Main Aim of spring dependency checking is make sure all the properties of spring bean have been set.

    If we want to apply dependency checking for particular property then we need to apply @Required Annotation.

    How to apply @Required Annotation?

    The @Required annotation applies to setter methods of bean property like following.

    public class Person{
    private String personName;
    
    @Required
    public void setPersonName(String personName) {
     this.personName = personName;
     }
    }
    
    

    In Above we have applied @Required on top of setter method of personName property of Person Bean.That means we must need to set the value of personName property in spring configuration file.



    what is mean by @Required Annotation?

    If We apply @Required Annotation on top of any setter method of bean property then that property have been must be set in configuration file,through an explicit property value in a bean definition.

    what changes need to in spring configuration file(applicationContext.xml)?

    1.we need to add to spring configuration file.

    2.To Enable the @Required annotation, in spring configuration file we need to register RequiredAnnotationBeanPostProcessor like following

    
    

    Lets see An Example For Spring dependency checking with @Required Annotation.

    The Project Structure:

    1.in src/main/java contains all java model classes.

    2.src/main/resources contains all configuration files and properties files.

    3.src/main/test contains all Test classes.


    pom.xml

    
      4.0.0
      Test2
      Test2
      0.0.1-SNAPSHOT
      
      
     org.springframework
     spring-core
     3.2.6.RELEASE
    
      
     org.springframework
     spring-beans
     3.2.6.RELEASE
    
      
     org.springframework
     spring-context
     3.2.6.RELEASE
    
      
    
    
    

    Person.java

    package com.javalschool.dependencycheck;
    
    import org.springframework.beans.factory.annotation.Required;
    
    public class Person {
     private  int personId;
     private String personName;
     private Address address;
     public int getPersonId() {
      return personId;
     }
     public void setPersonId(int personId) {
      this.personId = personId;
     }
     public String getPersonName() {
      return personName;
     }
     @Required
     public void setPersonName(String personName) {
      this.personName = personName;
     }
     public Address getAddress() {
      return address;
     }
     public void setAddress(Address address) {
      this.address = address;
     }
     @Override
     public String toString() {
      return "Person [personId=" + personId + ", personName=" + personName
        + ", address=" + address + "]";
     }
     
    
    }
    
    

    In Above we have applied @Required annotation on top of personName property of Person Bean.so we must need to set the value of personName in spring configuratioin File.


    Address.java

    package com.javalschool.dependencycheck;
    
    public class Address {
     private String flatNo;
     private String street;
     public String getFlatNo() {
      return flatNo;
     }
     public void setFlatNo(String flatNo) {
      this.flatNo = flatNo;
     }
     public String getStreet() {
      return street;
     }
     public void setStreet(String street) {
      this.street = street;
     }
     @Override
     public String toString() {
      return "Address [flatNo=" + flatNo + ", street=" + street + "]";
     }
     
    }
    
    

    applicationContext.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
     <context:annotation-config />
     &lbean
      class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
     <bean id="personBean" class="com.javalschool.dependencycheck.Person">
      
      <property name="personId" value="12345" />
       <property name="personName" value="ABCDE" />
      <property name="address" ref="addressBean" />
     </bean>
     <bean id="addressBean" class="com.javalschool.dependencycheck.Address">
      <property name="flatNo" value="2-3/45" />
      <property name="street" value="xxxxxxx" />
     </bean>
    </beans>
    

    Create Test class and Run it

    package com.javalschool.test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.javalschool.dependencycheck.Person;
    
    public class Test {
    
     @SuppressWarnings("resource")
     public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
      Person person = (Person) context.getBean("personBean");
      System.out.println(person.toString());
    
     }
    
    }
    
    

    output:

    log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
    log4j:WARN Please initialize the log4j system properly.
    Person [personId=12345, personName=ABCDE, address=Address [flatNo=2-3/45, street=xxxxxxx]]
    

    Constructor in java with Example


    what is constructor in java?

    constructor in java is some piece of code which is executed automatically at the time of object creation. The Main aim of constructor is to perform initialization for newly created objects.

    In java Every Time we create a new object, atleast one constructor is invoked.in java every class has a constructor,if we don't create a constructor also the compiler will create one one constructor.

    Rules To define Constructor in java:

    1. The Name of class and the constructor name must be same.
    2. constructors cannot have return types not even void also(if we put any return type we wont get any compile time and runtime errors but compiler trearts it as a normal method).
    3. The applicable modifiers for modifiers are public protectd private,default.

    Types of constructors in java

    1. default constructors
    2. parameterized constructor

    1.default constructor in java:

    In Java if We are not defining any constructor the compiler will generate one default constructor.

    The default has no arguments.

    The default constructor has the same access modifiers as the class.

    The Default constructor includes a no-arg call to the super constructor(super()).

    syntax of default constructor in java:

    (){
    }
    

    Example to default constructor in java:

    package javaprograms;
    
    public class DefaultConstDemo {
    
     
     public DefaultConstDemo() {
      System.out.println("im invoked when new object is created");
     }
    
     public static void main(String[] args) {
    
        DefaultConstDemo defaultcontdemo = new DefaultConstDemo();
     }
    
    }
    
    

    output:

    im invoked when new object is created
    

    in above class we kept one default constructor and that is invoking when new object is creating.

    2.parameterized constructor in java

    The parameterized constructor in java means that can have multiple parameters.

    syntax of parameterized constructor in java:

    <class-name>(parameter1,parameter2........){
    this.parameter1=value1;
    this.parameter2= value2;
    ..........
    }
    

    Example to parameterized constructor in java

    package javaprograms;
    
    public class Employee {
     private int  employeeId;
     private String employeeName;
     private  double employeeSalary;
     
    
     public Employee(int employeeId, String employeeName, double employeeSalary) {
      this.employeeId = employeeId;
      this.employeeName = employeeName;
      this.employeeSalary = employeeSalary;
     }
      
      public void viewEmployeeDetails(){
      System.out.println("The Employee id :"+employeeId);
      System.out.println("The Employee name:"+employeeName);
      System.out.println("The Employee Salary:"+employeeSalary);
       
      }
    
     public static void main(String[] args) {
      Employee employee = new Employee(10001,"ABCDD",12345.00);
      employee.viewEmployeeDetails();
      
     
    
     }
    
    }
    
    

    output:

    The Employee id :10001
    The Employee name:ABCDD
    The Employee Salary:12345.0
    
    

    constructor overloading in java:

    In Java a class can have more than one constructors with same name but different parameters such type of constructors are called as overloaded constructors.

    Example to constructor overloading in java:

    package javaprograms;
    
    public class Employee1 {
     private int  employeeId;
     private String employeeName;
     private  double employeeSalary;
    
    
     public Employee1(int employeeId, String employeeName) {
     
      this.employeeId = employeeId;
      this.employeeName = employeeName;
     }
    
    
     public Employee1(int employeeId, String employeeName, double employeeSalary) {
      super();
      this.employeeId = employeeId;
      this.employeeName = employeeName;
      this.employeeSalary = employeeSalary;
     }
    
    
      public void showDetails()
      {
       System.out.println("The Employee Details are "+employeeId+" "+employeeName+" "+employeeSalary);
      }
    
     public static void main(String[] args) {
      Employee1 employee1 = new Employee1(2,"BBBB");
      
      Employee1 employee2 = new Employee1(1,"AAAAA",9394049.00);
      employee1.showDetails();
      employee2.showDetails();
      
    
     }
    
    }
    
    

    output:

    The Employee Details are 2 BBBB 0.0
    The Employee Details are 1 AAAAA 9394049.0
    

    Life cycle of a Thread in Java


    NewState:

    Once we created an instance of Thread class Then The Thread will be New state.

    Runnable state:

    When we call start() method Then The thread will be entered into Runnable state.

    Runnable state:

    When we call start() method Then The thread will be entered into Runnable state.

    Non-Runnable state:

    In This state thread will Block for some period (or) some circumstance.A Thread Remains in a Not-runnable state until a special transition occurs.


    Spring Dependency Checking


    The Main Aim of dependency checking in spring to make sure the required properties have been set or injected.

    To define the spring dependency check In Spring Configuration File We need to declare one attribue "dependency-check".

    In Spring dependency checking works only if a property has been injected through the Setter Method.

    dependency check values:

    1. none
    2. simple
    3. objects
    4. all

    none:

    it is default depency check mode.No Dependency checking.

    simple:

    Dependency checking is applied on primitive types(int,float,double..) and collection types(list,set,map..). if any properties of primitive type(int,long,double...) and collections(list,set,map...) have not been set,UnsatisfiedDependencyException will be thrown.

    objects:

    Dependency checking applied on obejct(secondary) types. If any properties of Object(Secondary) type have not been set,UnsatisfiedDependencyException will be thrown.

    all:

    If any properties either primitive types or object types have not been set,UnsatisfiedDependencyException will be thrown. to make all primitives and secondary both are mandatory.

    Lets see an example For Spring Dependency checking.

    Person.java

    package com.javalschool.dependencyExample;
    
    public class Person {
    private String personId;
    private String personName;
    private Address address;
    public String getPersonId() {
     return personId;
    }
    public void setPersonId(String personId) {
     this.personId = personId;
    }
    public String getPersonName() {
     return personName;
    }
    public void setPersonName(String personName) {
     this.personName = personName;
    }
    public Address getAddress() {
     return address;
    }
    public void setAddress(Address address) {
     this.address = address;
    }
    @Override
    public String toString() {
     return "Person [personId=" + personId + ", personName=" + personName
       + ", address=" + address + "]";
    }
    
    }
    

    Address.java

    package com.javalschool.dependencyExample;
    
    public class Address {
     private String flatNo;
     private String street;
     public String getFlatNo() {
      return flatNo;
     }
     public void setFlatNo(String flatNo) {
      this.flatNo = flatNo;
     }
     public String getStreet() {
      return street;
     }
     public void setStreet(String street) {
      this.street = street;
     }
     
     
    
    }
    
    

    dependency checking:none

    The following code for when the dependency checking is none.In this mode we no need to call any setter methods.

    
     
    
    
    
    
    
    
    
    

    Test.java

    package com.javalschool.dependencyExample;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    
    
    public class Test {
    
     public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
      Person person = (Person)context.getBean("personBean");
      System.out.println(person.toString());
      
            
     }
    
    }
    
    

    output:

    log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
    log4j:WARN Please initialize the log4j system properly.
    Person [personId=12345, personName=AAAAAA, address=null]
    

    dependency checking:simple

    The Following code for when the dependency checking is simple. In This Mode We must need to call primitive and collection setter methods.For Dependency checking simple mode we need to "dependency-check= simple" attribute to bean tag.

    In above application we need to change like Following.

    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
      "http://www.springframework.org/dtd/spring-beans.dtd">
     
    
    
    
    
    
    
    

    output:

    log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
    log4j:WARN Please initialize the log4j system properly.
    Person [personId=12345, personName=AAAAAA, address=null]
    
    

    Note: In above if we not call any primitive setter method we will get following Exception

    Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'personBean' defined in class path resource [applicationContext.xml]: Unsatisfied dependency expressed through bean property 'personId': Set this property value or disable dependency checking for this bean. will be thrown.


    dependency checking:objects

    The Following code for when the dependency checking id objects..In This Mode We must need to call object type setter methods.

    
     
    
    
    
    
    
    
    
    
    
    

    Output:

    log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
    log4j:WARN Please initialize the log4j system properly.
    Person [personId=null, personName=null, address=Address [flatNo=2-3/45, street=xxxxxxx]]
    
    
    

    Note:If We not call any objct type setter method we will get UnsatisfiedDependencyException

    Spring Bean Definition Inheritance


    Spring supports bean configuration inheritance.Normally A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name.

    A child bean definition inherits configuration data from a parent bean definition.

    The child definition can override the inherited values.

    by using spring Bean Inheritance we can define a bean and configure in spring configuration file to create new bean.

    Lets See An Example For Spring Bean Definition Inheritance

    The Project Structure



    Person.java

    package com.javalschool;
    public class Person {
     private String personId;
     private String personName;
     private String Address;
     public String getPersonId() {
      return personId;
     }
     public void setPersonId(String personId) {
      this.personId = personId;
     }
     public String getPersonName() {
      return personName;
     }
     public void setPersonName(String personName) {
      this.personName = personName;
     }
     public String getAddress() {
      return Address;
     }
     public void setAddress(String address) {
      Address = address;
     }
     @Override
     public String toString() {
      return "Person [personId=" + personId + ", personName=" + personName
        + ", Address=" + Address + "]";
     }
     
    
    }
    

    Spring Configuration file applicationContext.xml

    
     
    
    
    
    
    
    
    
    
    

    In Above "personBean" is parent bean and "childBean" is known as child bean and inheriting property is "address" and adding new properties are "personId" and "personName".in above spring container is creating "childBean(child bean)" by defining "personBean(parent bean)" in Spring cofiguration file.

    Create a Test class and Run it(Test.java)

    package com.javalschool;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Test {
    
     public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
      Person person = (Person)context.getBean("childBean");
      System.out.println(person.toString());
    
     }
    
    }
    
    

    output:

    log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
    log4j:WARN Please initialize the log4j system properly.
    Person [personId=12345, personName=AAAAAA, Address=Bangalore]
    
    

    Hibernate Criteria With Example


    Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. That Means Whenever retriving entiies from a database using Criteria,we can apply condition using Criterion.

    First we need Criterion object and then we need to add Criterion object to Criteria object.

    An object-oriented representation of a query criterion that may be used as a restriction in a Criteria query. Built-in criterion types are provided by the Restrictions factory class. This interface might be implemented by application classes that define custom restriction criteria. Criterion is an interface available in org.hibernate.criterion package.

    Criterion instances are usually obtained via the Factory methods on Restrictions.

    We can use The static factory methods of org.hibernate.criterion.Restrictions class to create built in criterion types

    Structure of Criterion instance:

    Criteria cr = session.createcriteria(Student.class);
    Criterion condition = Restrictions.eq(“name”,”bala”);
    Cr.add(condition);
    List list = cr.list();
    

    Lets See An Example For Hibernate Criteria

    The Project structure:

    Employee.java.

    package com.javalschool;
    public class Employee {
     private int employeeId;
     private String employeeName;
     private double salary;
     public int getEmployeeId() {
      return employeeId;
     }
     public void setEmployeeId(int employeeId) {
      this.employeeId = employeeId;
     }
     public String getEmployeeName() {
      return employeeName;
     }
     public void setEmployeeName(String employeeName) {
      this.employeeName = employeeName;
     }
     
     public double getSalary() {
      return salary;
     }
     public void setSalary(double salary) {
      this.salary = salary;
     }
     @Override
     public String toString() {
      return "Empoyee [employeeId=" + employeeId + ", employeeName="
        + employeeName + ", salary=" + salary + "]";
     }
     
    
    }
    
    
    

    And Next you need add the all Hibernate jar files to buildpath.

    Hibernate.cfg.xml

    <!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
     
     
     
     
       oracle.jdbc.driver.OracleDriver
       
       jdbc:oracle:thin:@localhost:1521:XE
       
       system
       1234
       
       update
       org.hibernate.dialect.OracleDialect
       true
       
       
     
     
    

    employee.hbm.xml

    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
        
       
        
        
        
        
        
        
         
        
        
    

    Test.java

    package com.javalschool;
    
    import org.hibernate.Criteria;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.criterion.Criterion;
    import org.hibernate.criterion.Restrictions;
    
    public class Test {
     public static void main(String[] args) {
      // TODO Auto-generated method stub
      Configuration cfg = new Configuration();
      cfg.configure();
      SessionFactory factory = cfg.buildSessionFactory();
      Session session = factory.openSession();
      
      Criteria crit = session.createCriteria(Employee.class);
      Criterion condition = Restrictions.eq("employeeId",1234);
      crit.add(condition);
      Employee employee= (Employee)crit.uniqueResult();
      System.out.println(employee.getEmployeeName());
      System.out.println(employee.getSalary());
      
      Transaction tx = session.beginTransaction();
      
      
      
     
      tx.commit();
      System.out.println("done");
      session.close();
      factory.close();
     
      
      
    
     }
    
    }
    
    
    

    output:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Hibernate: select this_.eid as eid0_0_, this_.ename as ename0_0_, this_.salary as salary0_0_ from employee17 this_ where this_.eid=?
    BBB
    15000.0
    done
    
    
    

    >

    In My database table employee17 like this


    Interface in java with Examples


    Interface is a service requirement specification.

    We can declare an Interface with interface keyword.

    The structure of Interface:

    public interface Car {
    }
    

    interface is a collection of public static final variables and public and abstract methods.

    Every variables present in interface is public ,static, final by default.

    Every method present in interface is public abstract methods bydefault.

    interface itself implicitly public abstract.

    Interface Syntax :

    interface interfacename{
     public static finale int x = 10;//public static final variables;
    public abstract show();//public abstract methods;
    }
    

    Bullet points about interfaces:

    interfaces are totally incomplete classes.

    we cannot create object  directly to the interface but we can create object indirectly.

    we have to provide implementation for the interface methods is possible only in its implementation class

    all variables in interface have to be initialized in interface only.

    interface must be implemented in its child class and have to provide implementation for all the methods present in interface.

    A class can extend only one class.

    A class can implement ‘n’ number of interfaces.

    An interface can extends more than one interface.

    Interface cannot implements or extends a class. Since defined things cannot be made as undefined things.

    Interfaces should not be final.

    An interface does not contain Constructors.

    inside interface we are not allowed to write any static blocks and instance blocks.


    Lets see An Example For Interface:

    package com.javalschool;
    
    public interface Car {
     public abstract void wheels();
     public abstract void engine();
    
    }
    
    
    public class Test10 implements Car {
    
     @Override
     public void wheels() {
      System.out.println("car has 4 wheels");
    
     }
    
     @Override
     public void engine() {
      System.out.println(" car has one engine");
    
     }
    
     /**
      * @param args
      */
     public static void main(String[] args) {
      Test10 t = new Test10();
      t.engine();
      t.wheels();
    
     }
    
    }
    
    

    Output:

     car has one engine
    car has 4 wheels
    
    

    interface can extends many interface at a time.

    Example:

    public interface  vehicle extends bus,car{
    }
    

    What is Marker interface?

    it is an interface and it does not contain any methods.such type of interfaces are is known as marker interface.

    EX:Serializable interface.

    Hibernate Inheritance:Table Per Concrete Class (XML Mapping) Hierarchy With Example


    Table Per Concrete class Hierarchy we map the class Hierarchy to Multiple Tables. In Table Per Concrete Class Hierarchy Hibernate uses a separate Table for storing the generalized attribute and specialized attributes of child class.

    In this strategy we need to "<union-subclass>" tag in Mapping File to represent Table PerHConcrete Class hierarchy.

    Lets See an Example For Table Per Concrete Class Hierarchy in Hibernate.

    The Project structure:


    Person.java

    package org.javalschool;
    
    public class Person {
     private int personId;
     private String personFirsrtName;
     private String personLastName;
     public int getPersonId() {
      return personId;
     }
     public void setPersonId(int personId) {
      this.personId = personId;
     }
     public String getPersonFirsrtName() {
      return personFirsrtName;
     }
     public void setPersonFirsrtName(String personFirsrtName) {
      this.personFirsrtName = personFirsrtName;
     }
     public String getPersonLastName() {
      return personLastName;
     }
     public void setPersonLastName(String personLastName) {
      this.personLastName = personLastName;
     }
     
    
    }
    
    

    Student.java

    package org.javalschool;
    
    public class Student extends Person {
     private int studentClass;
     private String Branch;
     public int getStudentClass() {
      return studentClass;
     }
     public void setStudentClass(int studentClass) {
      this.studentClass = studentClass;
     }
     public String getBranch() {
      return Branch;
     }
     public void setBranch(String branch) {
      Branch = branch;
     }
     
    
    }
    
    

    Teacher.java

    package org.javalschool;
    
    public class Teacher extends Person {
     private String department;
     private String subject;
     public String getDepartment() {
      return department;
     }
     public void setDepartment(String department) {
      this.department = department;
     }
     public String getSubject() {
      return subject;
     }
     public void setSubject(String subject) {
      this.subject = subject;
     }
     
    
    }
    
    

    person.hbm.xml"

    
    
    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
        
       
        
        
        
        
        
        
           
         
        
        
        
        
          
        
        
        
       
         
        
        
    

    hibernate.cfg.xml

    <!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
     
     
     
     
       oracle.jdbc.driver.OracleDriver
       
       jdbc:oracle:thin:@localhost:1521:XE
       
       system
       1234
       
       update
       org.hibernate.dialect.OracleDialect
       true
       
       
     
     
    

    Test.java"

    package org.javalschool1;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    
    public class Test {
     public static void main(String[] args) {
      // TODO Auto-generated method stub
      Configuration cfg = new Configuration();
      cfg.configure();
      SessionFactory factory = cfg.buildSessionFactory();
      Session session = factory.openSession();
      Person p = new Person();
      p.setPersonId(2017);
      p.setPersonFirsrtName("Mankali");
      p.setPersonLastName("bala");
      
      Teacher teacher = new Teacher();
      teacher.setPersonId(10015);
      teacher.setPersonFirsrtName("AAA");
      teacher.setPersonLastName("bbb");
      teacher.setDepartment("physics");
      teacher.setSubject("networks");
      
      Student student = new Student();
      student.setPersonId(10011);
      student.setPersonFirsrtName("Srikanth");
      student.setPersonLastName("deva");
      student.setBranch("EEE");
      student.setStudentClass(2);
      
      
      session.save(p);
      session.save(student);
      session.save(teacher);
      
      
      Transaction tx = session.beginTransaction();
     //session.save(s);
      tx.commit();
      session.close();
      factory.close();
      System.out.println("successfully inserted");
      
      
    
     }
    
    }
    
    

    OutPut:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Hibernate: insert into person12 (pfirstname, pLastName, pid) values (?, ?, ?)
    Hibernate: insert into Student20 (pfirstname, pLastName, class, branch, pid) values (?, ?, ?, ?, ?)
    Hibernate: insert into teacher20 (pfirstname, pLastName, department, subject, pid) values (?, ?, ?, ?, ?)
    successfully inserted
    
      

    In database We will see The Output Like Following:

    select * from person12 ;

    select * from Student20;

    select * from teacher20;

    Hibernate Inheritance:Table Per SubClass(XML Mapping) Hierarchy With Example


    In Table Per SubClass strategy We Map The class Hierarchy to Multiple Tables associated with the relational ForeignKey. That Means Hibernate uses a separate Table for storing the parent class properties and separate table for each child class properties for storing the child class properties. To maintain relationship between these parent class table and child class tables hibernate uses ForeignKey relationship.

    In this strategy we need to use "<joined-subclass>" tag in Hibernate Mapping File to represent This Hibernate Inheritance strategy.

    Lets See an Example To Table Per SubClass XML Mapping in Hibernate Inheritance.

    The Project Structure:


    Person.java

    package org.javalschool;
    public class Person {
     private int personId;
     private String personFirsrtName;
     private String personLastName;
     public int getPersonId() {
      return personId;
     }
     public void setPersonId(int personId) {
      this.personId = personId;
     }
     public String getPersonFirsrtName() {
      return personFirsrtName;
     }
     public void setPersonFirsrtName(String personFirsrtName) {
      this.personFirsrtName = personFirsrtName;
     }
     public String getPersonLastName() {
      return personLastName;
     }
     public void setPersonLastName(String personLastName) {
      this.personLastName = personLastName;
     }
     
    
    }
    
    

    Student.java

    package org.javalschool;
    
    public class Student extends Person {
     private int studentClass;
     private String Branch;
     public int getStudentClass() {
      return studentClass;
     }
     public void setStudentClass(int studentClass) {
      this.studentClass = studentClass;
     }
     public String getBranch() {
      return Branch;
     }
     public void setBranch(String branch) {
      Branch = branch;
     }
     
    
    }
    
    

    Teacher.java

    package org.javalschool;
    public class Teacher extends Person {
     private String department;
     private String subject;
     public String getDepartment() {
      return department;
     }
     public void setDepartment(String department) {
      this.department = department;
     }
     public String getSubject() {
      return subject;
     }
     public void setSubject(String subject) {
      this.subject = subject;
     }
     
    
    }
    
    

    person.hbm.xml

     
    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
        
       
        
        
        
        
        
        
           
          
        
        
        
        
          
         
        
        
       
         
        
        
       

    hibernate.cfg.xml

    <!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
     
     
     
    oracle.jdbc.driver.OracleDriver
       
       jdbc:oracle:thin:@localhost:1521:XE
       
       system
       1234
       
       update
       org.hibernate.dialect.OracleDialect
       true
       
       
     
     
     

    Test.java

    package org.javalschool;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    public class Test {
    
      public static void main(String[] args) {
      // TODO Auto-generated method stub
      Configuration cfg = new Configuration();
      cfg.configure();
      SessionFactory factory = cfg.buildSessionFactory();
      Session session = factory.openSession();
      Person p = new Person();
      p.setPersonId(2017);
      p.setPersonFirsrtName("Mankali");
      p.setPersonLastName("bala");
      
      Teacher teacher = new Teacher();
      teacher.setPersonId(10015);
      teacher.setPersonFirsrtName("AAA");
      teacher.setPersonLastName("bbb");
      teacher.setDepartment("physics");
      teacher.setSubject("networks");
      
      Student student = new Student();
      student.setPersonId(10011);
      student.setPersonFirsrtName("Srikanth");
      student.setPersonLastName("deva");
      student.setBranch("EEE");
      student.setStudentClass(2);
      
      
      session.save(p);
      session.save(student);
      session.save(teacher);
      
      
      Transaction tx = session.beginTransaction();
     //session.save(s);
      tx.commit();
      session.close();
      factory.close();
      System.out.println("successfully inserted");
      
      
    
     }
    
    }
    
    

    OutPut:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Hibernate: insert into person10 (pfirstname, pLastName, pid) values (?, ?, ?)
    Hibernate: insert into person10 (pfirstname, pLastName, pid) values (?, ?, ?)
    Hibernate: insert into Student2017 (class, branch, personid) values (?, ?, ?)
    Hibernate: insert into person10 (pfirstname, pLastName, pid) values (?, ?, ?)
    Hibernate: insert into teacher2017 (department, subject, personid) values (?, ?, ?)
    successfully inserted
    

    In Database we willl see output like Following:

    select * from person10;

    select * from Student2017;

    select * from teacher2017;



    Hibernate Inheritance:Table Per Class Hierarchy(XML Mapping) With Example


    In This Table per class hierarchy Inheritance strategy We map the entire class hierarchy to a single Table.That means a single table used to represent the entire class hierarchy.

    This single table used to represent The entire class hierarchy.

    This single table includes the columns for the properties for all classes in the Hierarchy.

    In This Strategy ,we need an extra column in database table called discriminator column.

    Discriminator column stores the value which is used to recognize the one Derived class object among multiple derived classes in database.

    In this strategy Discriminator column is mandatory otherwise we will get exception.

    In this Hierarchy we need to use "<subclass>" tag in Hibernate Mapping File to represent The Hibernate Inheritance Hierarchy.

    Advantages:

    1. This approach of inheritance is basic and easy to use.
    2. It is efficient compared to other two approaches.

    Disadvantages:

    1. The columns for properties declared by subclass must be declared to accept null value.That means These columns cannot be declared with "NOTNULL" constraint.
    2. This drawback causes to problem for data integrity.

    The Project Structure:



    Person.java

    package com.javalschool;
    public class Person {
     private int personId;
     private String personFirsrtName;
     private String personLastName;
     public int getPersonId() {
      return personId;
     }
     public void setPersonId(int personId) {
      this.personId = personId;
     }
     public String getPersonFirsrtName() {
      return personFirsrtName;
     }
     public void setPersonFirsrtName(String personFirsrtName) {
      this.personFirsrtName = personFirsrtName;
     }
     public String getPersonLastName() {
      return personLastName;
     }
     public void setPersonLastName(String personLastName) {
      this.personLastName = personLastName;
     }
     
    
    }
    
    

    Student.java

    package com.javalschool;
    
    public class Student extends Person {
     private int studentClass;
     private String Branch;
     public int getStudentClass() {
      return studentClass;
     }
     public void setStudentClass(int studentClass) {
      this.studentClass = studentClass;
     }
     public String getBranch() {
      return Branch;
     }
     public void setBranch(String branch) {
      Branch = branch;
     }
     
    
    }
    
    

    Teacher.java

    package com.javalschool;
    public class Teacher extends Person {
     private String department;
     private String subject;
     public String getDepartment() {
      return department;
     }
     public void setDepartment(String department) {
      this.department = department;
     }
     public String getSubject() {
      return subject;
     }
     public void setSubject(String subject) {
      this.subject = subject;
     }
     
    
    }
    
    

    person.hbm.xml

    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    
        
       
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
            
        
        
    
    

    hibernate.cfg.xml

    <!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
     
     
     
    oracle.jdbc.driver.OracleDriver
       
       jdbc:oracle:thin:@localhost:1521:XE
       
       system
       1234
       
       update
       org.hibernate.dialect.OracleDialect
       true
       
       
     
     
     

    Test.java

    package com.javalschool;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    
    import com.javalschool.Student;
    
    public class Test {
    
     /**
      * @param args
      */
     public static void main(String[] args) {
      // TODO Auto-generated method stub
      Configuration cfg = new Configuration();
      cfg.configure();
      SessionFactory factory = cfg.buildSessionFactory();
      Session session = factory.openSession();
      Person p = new Person();
      p.setPersonId(2017);
      p.setPersonFirsrtName("Mankali");
      p.setPersonLastName("bala");
      Teacher teacher = new Teacher();
      teacher.setPersonFirsrtName("vinnay");
      teacher.setPersonId(5047);
      teacher.setPersonLastName("kanth");
      teacher.setDepartment("physics");
      teacher.setSubject("networks");
      Student student = new Student();
      student.setPersonId(10011);
      student.setPersonFirsrtName("Srikanth");
      student.setPersonLastName("deva");
      student.setBranch("EEE");
      student.setStudentClass(2);
      
      
      session.save(p);
      session.save(student);
      session.save(teacher);
      
      
      Transaction tx = session.beginTransaction();
    
      tx.commit();
      session.close();
      factory.close();
      System.out.println("done");
      
      
    
     }
    
    }
    
    

    OutPut

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Hibernate: insert into person1010 (pfirstname, pLastName, personType, pid) values (?, ?, 'com.javalschool.Person', ?)
    Hibernate: insert into person1010 (pfirstname, pLastName, class, branch, personType, pid) values (?, ?, ?, ?, 'student_person', ?)
    Hibernate: insert into person1010 (pfirstname, pLastName, department, subject, personType, pid) values (?, ?, ?, ?, 'teacher_person', ?)
    done
    
    
    

    In Database we will get output like Following:

    select * from person1010;



    Hibernate Second Level Cache With Example


    Second Level Cache always associates with the SessionFactory object. The Objects stored in second level cache will available to the entire application. Second level cache not enable by default.we need to enable it

    Second level cache implementations:

    1. EHcache(EasyHibernate cache)
    2. oscache(opensymphony cache)
    3. swarm cache
    4. JBoss Tree cache

    EHcache(EasyHibernate cache):

    1. This cache provider class is Org.hibernate.cache.Ehcacheprovider
    2. It supports memory-based caching.
    3. It supports Query cache support.
    4. It is Easy to use.
    5. Supports read-only and read/write caching.
    6. It doesnot support clustering.

    OScache(opensymphony cache)

    1. This Cache provider class is org.hibernate.cache.OScacheprovider
    2. It supports memory-based,disk based caching.
    3. It supports Query cache.

    swarmcache:

    1. The cahce provider class is org.hibernate.cache.swarmcacheprovider
    2. It supports cluster based caching.
    3. It supports read-only (or) nonstrict read/write caching.

    JBoss cache:

    1. The cache Provider class org.hibernate.cache.TreeCacheprovider
    2. It is transactional cache.

    Caching strategies:

    1. readonly
    2. read/write
    3. Nonstrict read-write
    4. Transactional

    readonly:

    If our application needs to read instances of persistent class,but needs to modify the persistent class then we will use Query Cache.

    Example:

    
    
    
    

    read/write:

    If our java application needs to update data then we will use read-write.

    
    
    
    

    Nonstrict read-write:

    If the java application needs to update data.

    
    
    
    

    Transactional:

    The Transactional cache strategy provider support for fully transactional cache provides such as JBoss Tree cache.

    It is only used JTA Environment.

    Steps to develop EHcache:

    step-1:

    In Hibernate Mapping File we need to add the following property

    
    

    Step-2:

    In Hibernate configuration file we need to add following class

    org.hibernate.cache.EhCacheProvider  
             true 
    	  echcache.xml
    

    step-3:

    Now create ehcache.xml like following

    
    
     
       
    
    

    Lets See An Example To Hibernate Second Level Cache

    The Project Structure:


    Employee.java


    package com.javalschool;
    
    public class Employee {
    
    	private int employeeId;
    	private String employeeName;
    	private double salary;
    	
    	public Employee() {
    		super();
    	}
    	public int getEmployeeId() {
    		return employeeId;
    	}
    	public void setEmployeeId(int employeeId) {
    		this.employeeId = employeeId;
    	}
    	public String getEmployeeName() {
    		return employeeName;
    	}
    	public void setEmployeeName(String employeeName) {
    		this.employeeName = employeeName;
    	}
    	public double getSalary() {
    		return salary;
    	}
    	public void setSalary(double salary) {
    		this.salary = salary;
    }
    	@Override
    	public String toString() {
    		return "Employee [employeeId=" + employeeId + ", employeeName="
    				+ employeeName + ", salary=" + salary + "]";
    	}
    	
    }
    
    

    hibernate.hbm.xml:


    
    <!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
        
        
       
        
        
        
        
        
        
        
        
    
    
    

    hibernate.cfg.xml:


    <!DOCTYPE hibernate-configuration PUBLIC
    	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    	
    	
    	  oracle.jdbc.driver.OracleDriver
    	  jdbc:oracle:thin:@localhost:1521:XE
    	  system
    	  1234
    	  
    	  update
    	  org.hibernate.dialect.OracleDialect
    	  true
    	  
    	   
    	   	org.hibernate.cache.EhCacheProvider  
             true 
    	  echcache.xml
    	  
    	  
    	  
    	
    	
    

    ehcache.xml


    
    
     
       
    
    

    Test.java

    package com.javalschool;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    
    public class Test {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Configuration cfg = new Configuration();
    		cfg.configure();
    		SessionFactory factory = cfg.buildSessionFactory();
    		Session session = factory.openSession();
    		
    		Object  o = session.get(Employee.class,5467);
    		Employee e = (Employee)o;
    		System.out.println(e.getEmployeeName());
    		Object o1 = session.get(Employee.class,5467);
    		Employee e1 = (Employee)o1;
    		System.out.println(e1.getEmployeeName());
    		Transaction tx = session.beginTransaction();
    		
    		tx.commit();
    		session.close();
    		factory.close();
    		System.out.println("done");
    		
    		
    
    	}
    
    }
    

    OutPut:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Hibernate: select employee0_.eid as eid0_0_, employee0_.ename as ename0_0_, employee0_.salary as salary0_0_ from employee25 employee0_ where employee0_.eid=?
    ABCD
    ABCD
    done
    


    Hibernate First Level Cache with Example


    First level cache always associates with the session object.Hibernate uses first-level-cache by default. In this cache with in the session if we call same query for any number of times Hibernate will generate only one select operation. First level cache useful for one user application.

    Lets See an Example For Hibernate First Level Cache.

    The Project Structure:

    Players.java

    package com.javalschool;
    
    public class Players {
    	private int playerId;
    	private String playerName;
    	
    	public Players() {
    		
    	}
    	
    	public int getPlayerId() {
    		return playerId;
    	}
    
    	public void setPlayerId(int playerId) {
    		this.playerId = playerId;
    	}
    
    	public String getPlayerName() {
    		return playerName;
    	}
    	public void setPlayerName(String playerName) {
    		this.playerName = playerName;
    	}
    	
    
    }
    
    
    

    players.hbm.xml:

    
    
        
        
        
        
        
        
        
        
        
    
    
    

    hibernate.cfg.xml:

    
    	
    	
    	  oracle.jdbc.driver.OracleDriver
    	  jdbc:oracle:thin:@localhost:1521:XE
    	  system
    	  1234
    	  
    	  update
    	  org.hibernate.dialect.OracleDialect
    	  true
    	  
    	  
    	
    	
    

    Test.java

    package com.javalschool;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    
    public class Test {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Configuration cfg = new Configuration();
    		cfg.configure();
    		SessionFactory factory = cfg.buildSessionFactory();
    		Session session =  factory.openSession();
    		Object o = session.get(Players.class,5240);
    		Players p = (Players)o;
    		System.out.println("Payer name is "+p.getPlayerName());
    		
    		p.setPlayerName("rama");
    		Object o1 = session.get(Players.class, 5240);
    		Players p1 = (Players)o;
    		System.out.println("player name is"+p1.getPlayerName());
    		
    		Object o2 = session.get(Players.class, 5240);
    		Players p2 = (Players)o;
    		System.out.println(p2.getPlayerName());
    		//Players p = new Players();
    		//p.//setPlayerId(5240);
    		//p.setPlayerName("Vinay");
    		
    		Transaction tx = session.beginTransaction();
    		session.save(p);
    		tx.commit();
    		
    		session.close();
    		factory.close();
    		System.out.println("successfully inserted");
    		
    		
    		
    
    	}
    
    }
    
    

    OutPut:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Hibernate: select players0_.pid as pid0_0_, players0_.pname as pname0_0_ from player20 players0_ where players0_.pid=?
    Payer name is rama
    player name israma
    rama
    successfully inserted
    


    Dependency Injection in Spring through Constructor Injection


    Constructor Injection is a process of injecting the dependencies of an object by using parameterized constructor.

    Lets See An example to how will do the dependency injection through the constructor.

    The Project Structure

    1.Product.java

    Product is a normal Java class.In the product class we have three properties and we have constructor with those three properties.


    package com.javalschool;
    
    public class Product {
     private int productId;
     private String productName;
     private String productPrice;
     
     
     public Product(int productId, String productName, String productPrice) {
      super();
      this.productId = productId;
      this.productName = productName;
      this.productPrice = productPrice;
     }
    
    
     @Override
     public String toString() {
      return "Product [productId=" + productId + ", productName="
        + productName + ", productPrice=" + productPrice + "]";
     }
    
    
     
    
    }
    
    

    2.Spring Configuation File(applicationContext.xml)

    Now Configue the spring bean in configuration File.The <constructor-arg> element describes one arguement of the constructor. whcich means to specify a constructor with multiple arguements we need to use the <costructor-arg>element multipletime in configuration file.


    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
      "http://www.springframework.org/dtd/spring-beans.dtd">
    
    
    
    
    
    
    
    
    

    3.Now create a Test class and Run it


    package com.javalschool;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class Test {
    
     public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext(
        "applicationContext.xml");
      Object o = context.getBean("product");
      Product product = (Product) o;
      System.out.println(product);
    
     }
    
    }
    
    

    4.output


    log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
    log4j:WARN Please initialize the log4j system properly.
    Product [productId=12345, productName=LED, productPrice=20000.00]