Wednesday, August 29, 2012

How to integrate Liquibase with Spring and Hibernate ?

A sample tutorial on how to integrate Liquibase with Spring and Hibernate.

While writing this tutorial, I have added javadoc in the code for better understanding and I believe You already have good knowledge on Spring and Hibernate. The main motto of this tutorial is to give an idea on how you can integrate Liquibase with Spring and Hibernate.

If you are new to Liquibase : Click Here

To integrate liquibase into your project, you need liquibase jars, So download it before starting the project.

I have created an application named "SHLIntegration". The Structure of the project is as follows :

The dependencies are also listed here:

Lets start with Employee class :

1. Create Employee class having getter/setter and add proper JPA annotation to each variable as below.

  public class Employee {

    @Id
    @GeneratedValue
    @Column(name="EMPLOYEE_ID")
    private long id;

    @Column(name="NAME")
    private String name;
   
    @Column(name="GENDER")
    private String gender;
   
    @Column(name="COUNTRY")
    private String country;
   
    @Column(name="ABOUT_YOU")
    private String aboutYou;

.....
....
.... // getter setter of each object

}

2. Create liquibase file i,e db-changelog.xml file

<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd">
       
    <changeSet author="waheed" id="123456789-1">
        <createTable tableName="EMPLOYEE">
            <column autoIncrement="true" name="EMPLOYEE_ID" type="BIGINT">
                <constraints nullable="false" primaryKey="true" />
            </column>
            <column name="NAME" type="VARCHAR(255)" />
            <column name="GENDER" type="VARCHAR(2)" />
            <column name="COUNTRY" type="VARCHAR(255)" />
            <column name="ABOUT_YOU" type="VARCHAR(255)" />
        </createTable>
    </changeSet>
</databaseChangeLog>




3. Add liquibase bean in your bean :

    <bean id="LiquibaseUpdater" class="liquibase.integration.spring.SpringLiquibase">
        <property name="dataSource" ref="dataSource" />
        <property name="changeLog" value="classpath:db-changelog.xml" />
    </bean>


 and others beans which are required for Spring/Hibernate.  Check bean file


The complete tutorial : 
https://github.com/abdulwaheed18/SHLIntegration


Please feel free to do comment or drop me a mail regarding any suggestion/Feedback.
Email : waheedtechblog@gmail.com















 


Some ANT task

1. How to build  project from another build.


<target name="project2"
            description="Builds project2 project, required depedency">
        <!-- Build project2 first  -->

        <subant target="dist" verbose="yes" inheritall="false">
            <filelist dir="../com.waheed.project2"
                      files="build.xml" />
        </subant>
    </target>

 

2. How to read SVN revision and write into some file


<loadfile property="revision" srcFile="./.svn/entries">
        <filterchain>
            <headfilter skip="3" lines="1"/>
                  </filterchain>
        </loadfile>
            <tstamp>
                <format property="date" pattern="dd/MM/yyyy hh:mm:ss" />
            </tstamp>
            <echo append="true" file="<FILE_NAME>" >revision=${revision}${line.separator}</echo>


3. How to generate Keystore


    <target name="keystore">
        <delete file="workdir/keystore" failonerror="false"/>
        <genkey keystore="./keystore"
                alias="jetty"
                storepass="password"
                keypass="password"
                keyalg="RSA"
                validity="10">
            <dname>
                <param name="CN" value="NAME" />
                <param name="OU" value="NAME_OF_ORGANIZATION_UNIT" />
                <param name="O" value="ORGANIZATION_NAME" />
                <param name="C" value="COUNTRY_NAME" />
            </dname>
        </genkey>
    </target>


4. How to get current time

<target name="time">
        <tstamp>
            <format property="build-time" pattern="yyyy-MM-dd-HH-mm" />
        </tstamp>
        <echo>${build-start-time}</echo>
    </target>


5 . How to create jar with manifest


 <jar jarfile="${dist}/name_of_jar.jar"
             basedir="${build}">
            <manifest>
                <!-- Who is building this jar? -->
                <attribute name="Built-By" value="${user.name}" />
                <!-- Information about the program itself -->
                <attribute name="Implementation-Vendor"
                           value="Implementation-Vendor" />
                <attribute name="Implementation-Title"
                           value="Implementation-Title" />
                <attribute name="Implementation-Version" value="1.0" />
                <!-- details -->
                <section name="PATH_TO_MAIN_CLASS">
                    <attribute name="Sealed" value="false" />
                </section>
            </manifest>
        </jar>


6. How to compile source


 <!-- Compile the java code from ${src} into ${build} -->

        <javac destdir="bin" debug="true">
            <src path="src" />
            <classpath>
                <pathelement location="../dependency/bin" />
                <fileset dir="../lib">
                    <include name="*.jar" />
                </fileset>
            </classpath>
        </javac>


7. How to compile source with dependency class path


 <path id="class.path">
        <fileset dir="../lib/folder1">
            <include name="*.jar" />
        </fileset>
        <fileset dir="../lib/folder2">
             <include name="*.jar" />
        </fileset>
    </path>


 <!-- Compile the java code from ${src} into ${build} -->
        <javac destdir="bin" debug="true">
            <src path="src" />
            <classpath refid="class.path" />
        </javac>



8.  How to build Zip file


    <property name="product.name" value="product1" />
    <property name="product.version" value="1.0" />

<zip basedir="${dist}" destfile="${dist}/${product.name}-${product.version}.zip">
        </zip>


9. How to build tar file

    <property name="product.name" value="product1" />
    <property name="product.version" value="1.0" />

<exec executable="tar" dir="${dist}">
            <arg value="czf" />
            <arg value="${dist}/${product.name}-${product.version}.tgz" />
            <arg value="." />
        </exec>

10 . How to check OS 


<condition property="isWindows">
        <os family="windows" />
    </condition>

    <condition property="isUnix">
        <os family="unix" />
    </condition>


    <target name="dist.windows" if="isWindows" depends="a">
<!--  Task to be done-- >
     </target>

    <target name="dist.unix" if="isUnix" depends="b">

<!--  Task to be done-- >
    </target>


11.  How to set permission to file


 <chmod perm="500">
            <fileset dir="${dist}">
                <include name="**/*.sh" />
                <include name="jsvc" />
            </fileset>
        </chmod>


12 .How to read property file

Suppose I have following data in my filename1.properties file and want to read it and write it to another file lets say name filename2.properties. 

filename1.properties
REVISION 777



     <property file="${dist}/filename1.properties" prefix="version"/>
       <echo file="${dist}/filename2.properties" append="true">revision ${version.REVISION}${line.separator}</echo>

Spring MVC tutorial

Before Starting, I believe you must have basic idea about JAVA, SPRING and Spring MVC.

For Spring MVC : http://waheedtechblog.blogspot.in/2012/08/spring-mvc.html

In this tutorial , I will just tell you what are the basic thing that you need to start MVC.

Step 1 : Create a class 


@Controller
public class HelloWorld {
 
    @RequestMapping("/hello")
    public String helloWorld() {
         return = "Hello World, Spring 3.0!";
    }
}


1 . The class HelloWorld  has the annotation @Controller and @RequestMapping("/hello"). When Spring scans this class, it will recognize this bean as being a Controller bean for processing requests. 2 .The @RequestMapping annotation tells Spring that this Controller should process all requests beginning with /hello in the URL path.

Step 2. Mapping Spring MVC in WEB.xml

The entry point of Spring 3.0 MVC is the DispatcherServlet. DispatcherServlet is a normal servlet class which implements HttpServlet base class. Thus we need to configure it in web.xml.

<!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

<!-- This loads the root webapp Spring context -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:beans.xml</param-value>
    </context-param>
   
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

Note that I have mapped /rest/* url pattern with example DispatcherServlet. Thus any url with /rest/* pattern will call Spring MVC Front controller.

                  The REST call would be http://ip:port/rest/hello

If your controller class has some dependency which you have defined in your spring context file.Then you have to load it in <context-param>.(red line).
Once the DispatcherServlet is initialized, it will looks for a file name [servlet-name]-servlet.xml in WEB-INF folder of web application. I have created the file named spring-servlet.xml


3 . Spring Configuration file

Create a file spring-servlet.xml in WEB-INF folder and copy following content into it.
<?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:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/task
    http://www.springframework.org/schema/task/spring-task-3.0.xsd
        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
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-2.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        ">

    <!-- ========================== -->
    <!-- Spring MVC: Core -->
    <!-- ========================== -->

    <context:annotation-config />
    <mvc:annotation-driven />
    <mvc:default-servlet-handler />

    <!-- class name of the controller or If you have package use component-scan -->
    <bean class="com.waheed.spring.hibernate.HelloWorld" />

 </beans>

The highlighted red line allow Spring to load the components from class. This will load our HelloWorld class.

Congratulation..!!! You are done here...

Download source code : https://github.com/abdulwaheed18/SpringMVC-Hibernate-Integration

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...