Saturday, September 7, 2013

Spring Data - JPA

A lot of effort is required for configuration and using JPA. Spring Data JPA has reduced that to a major extent. Takes little effort to configure and easy to use. Let's look at this with an example.
The spring data dependency and hibernate dependencies using maven are as follows. (Note: All other spring core, bean, context dependencies are required along with the below dependencies)
        <!-- Spring Data JPA -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.0.2.RELEASE</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
Create a persistence xml file in META-INF file.
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <!--Persistence Unit for Mysql database-->
    <persistence-unit name="testMysql" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.test.entity.Employee</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>
Now, need to configure Spring Data - JPA using the persistent unit "testMysql"
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--Following data source for Mysql-->
    <bean id="mysqltestDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.testurl}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--Following entity manager for Mysql database-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="mysqltestDataSource"/>
        <property name="persistenceUnitName" value="testMysql"/>
    </bean>

    <!--Transaction manager for both H2 and Mysql-->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>
    
    <jpa:repositories transaction-manager-ref="transactionManager" 
        entity-manager-factory-ref="entityManagerFactory" base-package="com.test.dao">
    </jpa:repositories>
    
</beans>
Explanation of above spring configuration Create one datasource.

  • Create one driver manager datasource named "mysqltestDataSource", by loading jdbc.properties file from the classpath using line <context:property-placeholder location="classpath:jdbc.properties"/>
  • Create entity manager factory using the datasource created and persistent unit created in persistent.xml
  • Inject entity manager factory into transaction manager. 
  • Finally configure both transaction manager and entity manager factory to set of repositories in a package (defined using base-package)
Now, create repository, an interface which extends JpaRepository inside package (defined in base-package). The typed arguments required are one entity and other is Id. In this case, entity is Employee and Id of the Employee is Long.
package com.test.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.test.entity.Employee;

public interface EmployeeDAO extends JpaRepository<Employee, Long>
{
}
The entity is as follows
package com.test.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "EMP")
@Entity
public class Employee
{
    private int id;
    private String name;
    private int age;
    @Id
    @Column(name = "id", unique = true, nullable = false)
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    @Column(name = "name")
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    @Column(name = "age")
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
}
That's it on the configuration part. By using the repository, we can do all types of database operations for that entity. There are numberous in-built methods are provided by JpaRepository interface. Sample code for that will be
        EmployeeDAO dao = (EmployeeDAO)context.getBean("employeeDAO");
        List list = dao.findAll();
        for(Employee e : list)
        {
            //Do Something
        }

Sunday, August 18, 2013

Java New IO 2.0

The New IO is one of the features introduced in Java7. A new package java.nio has been added as part of this feature. Even though the usage wise it's same as java.io, most of the issues in java.io has been addressed. We will see the features introduced in New IO (NIO)
Path
The package java.nio.file consists of classes and interfaces Path, Paths, FileSystem, FileSystems and others. Each of represent's the file path or file system as is.
java.nio.file.Path works exactly same as java.io.File with additional features.
Path path = Paths.get("C:\\temp\\sample.txt");
System.out.println("Name Count : "+path.getNameCount());
System.out.println("Parent     : "+path.getParent());
System.out.println("Root       : "+path.getRoot());
The output will be
Name Count : 2
Parent     : C:\temp
Root       : C:\
Files
Path can also be used for deleting. There are two delete methods. One delete method can throw NoSuchFileException if the file doesn't exist.
Files.delete(path);
Where as other deletes the file if exists.
Files.deleteIfExists(path);
There are copy, move, create (Both for directories and files) with options. There are mthods to create symbolic links, temporary directories as well.
WatchService
This is the service which we can get the file change notifications like delete, update, create, change etc. WatchService API makes to receive notifications on a file or directory.
   Path path = Paths.get("C:\\Temp");
   WatchService service = path.getFileSystem().newWatchService();
   path.register(service, StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY);
   WatchKey watckKey = service.take();
   List<watchevent>&gt; events = watckKey.pollEvents();
   for(WatchEvent event : events)
   {
       System.out.println("Event : "+event.kind().name()+"; Context : "+event.context());
   }
The steps for creating a WatchService are
  • Create WatchService instance using path
  • Register required events (Create, delete and modify are available) on the path
  • Get the watch key and poll for the events. (For continuously watching the events, put it in infinite loop).
Happy Learning!!!

Thursday, August 15, 2013

What's in .Class file - Contd.

This is continuation of post. Now, we will see bit in detail with an example
package com.test;
public class Employee
{
     .....
     public void setEmpid(int empid)
     {
          this.empid = empid;
     }
     ....    
     public double getSalary()
     {
          return salary;
     }
     public void setSalary(double salary)
     {
          this.salary = salary;
     }
}
For example, take the above block's byte code one by one
public void setEmpid(int);
  Code:
   0:   aload_0
   1:   iload_1
   2:   putfield        #2; //Field empid:I
   5:   return
The code is pretty readable. load means loading a value. Each load is prefixed by a character ( 'i' means integer, 'd' means decimal and 'a' means an object. putfield means setting a value to other variable. Each function will have a return statement at the end. If the function has a void return type, then simple return otherwise return will be prefixed by a character. For example getSalary() method as below
public double getSalary();
  Code:
   0:   aload_0
   1:   getfield        #4; //Field salary:D
   4:   dreturn
Each and every line in the java byte code is called opcode as we discussed has a special meaning. We can find the list of all opcodes in the JVM Spec or on Wiki. Apart from the load, put, get, return, new (That we saw). There are method invocations which you will find more common. These start with invoke prefix
  • invokespecial: Used to call the instance private as well as public method (including initializations)
  • invokevirtual : Used to call a method based on the class of the object. 
  • invokestatic : Invokes a static method. 
  • so on....
Will post some more details in the next posts.

Sunday, July 28, 2013

Spring OXM

OXM is Spring's Object/XML Mapping support which helps in conversion of Object to XML(Marshalling) and XML to Object(Unmarshalling). For this, spring has two interfaces Marshaller and Unmarshaller defined in spring-oxm under the package org.springframework.oxm.Marshaller . These can be defined as normal beans like other spring beans.
Marshaller and Unmarshaller has one method each for the actions as below.
public interface Marshaller {
    /**
     * Marshals the object graph with the given root into the provided Result.
     */
    void marshal(Object graph, Result result) throws XmlMappingException, IOException;
}
public interface Unmarshaller {
    /**
     * Unmarshals the given provided Source into an object graph.
     */
    Object unmarshal(Source source) throws XmlMappingException, IOException;
}
Implementation:
There are different marshaller instances in spring-oxm. We will go through CastorMashaller because it's easy to implement and configure.
<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="converter" class="com.test.spring.oxm.converter.Converter">
  <property name="marshaller" ref="castorMarshaller" />
  <property name="unmarshaller" ref="castorMarshaller" />
 </bean>
 
 <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
  <property name="mappingLocation" value="classpath:mapping.xml" />
 </bean>
</beans>
CastorMarshaller is the marshaller and it requires one optional property "mappingLocation" which defines the mapping of class to xml. Sample mapping.xml file is
<?xml version="1.0" encoding="UTF-8"?>
<mapping>
 <class name="com.test.spring.oxm.entity.Employee">
  <map-to xml="employee" />
  <field name="empid" type="integer">
   <bind-xml name="id" node="element" />
  </field>
  <field name="name" type="string">
   <bind-xml name="ename" node="element" />
  </field>
   <field name="dob" type="date" >
   <bind-xml name="dob" node="element"  />
  </field>
   <field name="salary" type="double">
   <bind-xml name="salary" node="element" />
  </field>
 </class>
</mapping>
Points to be noted
  • property "mappingLocation" is optional. We can create CastorMarshaller without mappingLocation but it takes default values while binding
  • Each class tag defines the Object which to be marshalled/unmarshalled with set of field tags. Each corresponds to XML and object mapping.
  • type on the field indicates the type of the node and is mapped to Java Type.
  • map-to and bind-xml tags defines the elements and attributes in the xml. 
  • node attribute in bind-xml defines whether the field should be attribute or element

Code for bean "converter" is as below. Converter internally calls the marshall and unmarshall methods of CastorMarshaller.
package com.test.spring.oxm.converter;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;

public class Converter
{
    private Marshaller marshaller;
    private Unmarshaller unmarshaller;

    public Marshaller getMarshaller()
    {
        return marshaller;
    }

    public void setMarshaller(Marshaller marshaller)
    {
        this.marshaller = marshaller;
    }

    public Unmarshaller getUnmarshaller()
    {
        return unmarshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller)
    {
        this.unmarshaller = unmarshaller;
    }
    
    public String convertToXml(Object obj,String filepath)
    {
        String finalString = new String();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filepath);
            getMarshaller().marshal(obj, new StreamResult(fos));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {
            if(fos != null)
            {
                try
                {
                    fos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return finalString;
    }
    
    public Object convertToObject(String filepath)
    {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filepath);
            return getUnmarshaller().unmarshal(new StreamSource(fis));
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally {
            if(fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
The object which to marshalled or unmarshalled is
package com.test.spring.oxm.entity;

import java.util.Date;

public class Employee
{
    private int empid;
    private String name;
    private Date dob;
    private Double salary;

    public int getEmpid()
    {
        return empid;
    }
    public void setEmpid(int empid)
    {
        this.empid = empid;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public Date getDob()
    {
        return dob;
    }
    public void setDob(Date dob)
    {
        this.dob = dob;
    }
    public Double getSalary()
    {
        return salary;
    }
    public void setSalary(Double salary)
    {
        this.salary = salary;
    }
}
Finally, the main program is
package com.test.spring.oxm;

import java.util.Date;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.test.spring.oxm.converter.Converter;
import com.test.spring.oxm.entity.Employee;

public class Application
{
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
        Converter converter = (Converter)context.getBean("converter");
        Employee emp = new Employee();
        
        emp.setDob(new Date());
        emp.setEmpid(1234);
        emp.setName("Employee Name");
        emp.setSalary(2500.122);
       
        converter.convertToXml(emp,"cust.xml");
        
        Employee emp2 = (Employee)converter.convertToObject("cust.xml");
        System.out.println("Empid : "+emp2.getEmpid());
        System.out.println("Name  : "+emp2.getName());
        System.out.println("Salary: "+emp2.getSalary());
        System.out.println("DOB   : "+emp2.getDob());
    }
}
The xml file generated out of it is :
<?xml version="1.0" encoding="UTF-8"?>
<employee>
 <id>1234</id>
 <ename>Employee Name</ename>
 <dob>2013-07-28T21:17:29.331+05:30</dob>
 <salary>2500.122</salary>
</employee>

Friday, July 26, 2013

What's in .Class File

I never looked what's inside .class file except knowing that .class file consists of compiled byte code of Java Program. I was looking at quite a few articles, specifications, posts etc to get to know about byte class exact contents.
We already know what compiler does, what is a byte code, how byte code is executed by jre. Below is the brief definition.
Byte code: Java compiler (javac) generates the byte code for each Java file compiled. Byte-code is a sequence of mnemonics. Each of them will be translated by java run time environment to execute.
There are many mnemonics byte code consists of. Let's take a look at some of them with some examples which are very frequent.
Example 1:
package com.test;
public class Main
{
     public static void main(String...args)
     {
          System.out.println("Hello World");
     }
}
After compiling the Main.java, the generated class file looks like as below when you open in any hexa-decimal supported editor.




















To view the byte code in ASCII, we can use javap command.
Example: javap <class-name> displays the Class with methods in it where as -c option shows the each line of code inside the methods.












There are some basic points in the above lines of byte-code. As we know, each and every class we write, will be a sub-class of java.lang.Object ( as we can see extends java.lang.Object even we don't have that in .java file) and a default constructor is added with no parameters.
javap prints more detailed information
-s : the internal signature
-l : the line numbers and local variables used inside each function
And to print all the information, just give -verbose. Sample output looks like this

Interesting fact is, even though the java file is so simple with very few statements, compiler generated very large set of statements with tables, signatures, etc. We will see the details of few instructions in the next posts.