Skip to main content

Maven project with Spring data JPA and Hibernate

Following example shows how to create simple system using Maven, Spring Data JPA with Hibernate.

 

01. Create Project structure as above. (I have used IntelliJ Idea 12 as IDE)
02. Create application-context.xml for spring configurations as follows

<?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 is for use H2 java embedded database-->
    <jdbc:embedded-database id="embeddedDataSource" type="H2"> </jdbc:embedded-database>

    <!--Following data source for Mysql-->
    <bean id="mysqlDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <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="mysqlDataSource"/>
        <property name="persistenceUnitName" value="smsBookingMysql"/>
    </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 base-package="org.sms.repository"> </jpa:repositories>

</beans>

In here "embeddedDataSource" bean use for create datasource using H2 java embeded database system and "mysqlDataSource" bean use for create Mysql data source.
We have to create entityManagerFactory (bean id = "entityManagerFactory") for create entityManger by using either one of above data sources. In here we have to introduce two properties

        <property name="dataSource" ref="mysqlDataSource"/>
        <property name="persistenceUnitName" value="smsBookingMysql"/>

"dataSource" for introduce which data source to be used from either "embeddedDataSource" or "mysqlDataSource" in my example
"persistenceUnitName" for the configure the which persistence unit going to be used. (persistence units must be configured in the persistence.xml as next step)

Next need to create transaction manage ( bean id = "transactionManager") for entity transaction and repository package as (in my example package would be "org.sms.repository")
<jpa:repositories base-package="org.sms.repository"> </jpa:repositories>

 03. Creat persistence.xml with persistence configurations for databases. In here, I'm used two kind of databases (persistence-unit) h2 and Mysql.

<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">

    <!--Persistence Unit for H2 database-->
    <persistence-unit name="smsBooking" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>org.sms.models.Post</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>

    <!--Persistence Unit for Mysql database-->
    <persistence-unit name="smsBookingMysql" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>org.sms.models.Post</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>

</persistence>

04 Create jdbc.properties file for Mysql configurations.

# Database connection settings
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://elg.scandium.db:3306/sms_booking?createDatabaseIfNotExist=true
jdbc.username = user
jdbc.password = password


05. Create simple repository call PostRepository.java

package org.sms.repository;

import org.sms.models.Post;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PostRepository extends JpaRepository<Post, Long> {
    //Create any additional repository calls if required
}


06. Create model class Post.java for database tables.

package org.sms.models;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "POST")
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "post_id")
    Long postId;

    @Column(name = "post_title")
    String title;

    @Column(name = "post_date")
    Date postDate;

    public Date getPostDate() {
        return postDate;
    }

    public void setPostDate(Date postDate) {
        this.postDate = postDate;
    }

    public Long getPostId() {
        return postId;
    }

    public void setPostId(Long postId) {
        this.postId = postId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

07. Above simple implementations are just enough for write simple test case for test the usage. Create PostRepositoyTest.java for test above repository functions.

package test;

import org.sms.models.Post;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.sms.repository.PostRepository;

import java.util.Date;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:META-INF/application-context.xml")
public class PostRepositoryTest {

    @Autowired
    PostRepository postRepository;

    @Test
    public void test() {
        Post post = new Post();
        post.setPostDate(new Date());
        post.setTitle("sms-title");

        postRepository.save(post);
        Post post1 = postRepository.findOne(post.getPostId());
        Assert.assertNotNull(post1);
        System.out.println(post1.getTitle());
    }
}

08. Go to the mevan parent pom.xml by terminal and run mvn clean install

parent pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>sms.booking</groupId>
    <artifactId>sms-booking</artifactId>
    <packaging>pom</packaging>
    <version>1.0.0</version>
    <modules>
        <module>orm</module>
        <module>core</module>
        <module>web</module>
    </modules>

    <properties>
        <spring.framework.version>3.2.2.RELEASE</spring.framework.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.3.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.0.60</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.2.0.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    </dependencies>
</project>


Clone the sample code from github

git clone https://github.com/malithmeee/spring-data-jpa-example.git

Refer the code https://github.com/malithmeee/spring-data-jpa-example

 

Comments

Popular posts from this blog

Prevent hot deployments memory leaks in Tomcat

Since we are mostly using Tomcat as App Container, it's making tough environment when deploying a patch or existing application without restarting tomcat server (Hot deployments) due to reaching the PermGen size due to memory leaks. Hence most of the cases we have to increase PermGen size more than required to deployed applications and it's wasting of memory in the system.  There is a solution for them to release PermGen size and let it clean by GC in JVM at hot deployment. Step 01: Include below dependency to pom.xml <dependency>               <groupId>se.jiderhamn.classloa der-leak-prevention</groupId>         <artifactId>classloader-leak-p revention-servlet</artifactId>   <version>2.2.0</version> </dependency> Step 02: Add listener to web.xml <listener>   <listener-class>se.jiderhamn.c lassloader.leak.prevention.Cla ssLoaderL...

Jboss 5.1.0_GA, Maven, Mysql, EJB3, JSF2 sample

I thought to write this because of no completed sample found with using above technologies. Environment JDK 1.6 Jboss-5.1.0.GA JSF2 Maven 3 EJB3 Note : Please copy the mysql connector jar to Jboss lib e.x. I copied mysql-connector-java-5.1.29.jar to jboss-5.1.0.GA/server/default/lib Clone the sample from github here git clone https://github.com/malithmeee/library.git Build the entire project and copy the library.ear to Jboss server. Try to access the web page using http://localhost:8080/library.web/home.jsf Note : Database needed to be created, and change properties in relevant files.

Birt Dynamic Table Creation from JDBC Mysql Connection with Maven

In this post refers how to create dynamic Birt reports using given customizing fields list using Birt Runtime 4.2.2 Step 01 : First need to download birt runtime. Download from here For view/Edit the rptdesign files, it's better to use Eclipes 4.2.2 Birt integration. Download eclipes here Step 02 : Extract the birt-runtime-4_2_2. and set the birt runtime home environment variable. e.g. in my case i'm set the environment variable in .bash_profile since i'm using Fedora. (we can specify the Birt home in java code as wel) export BIRT_HOME=/home/malith/usr/eclips/birt-runtime-4_2_2 Step 03 : Create Maven project and insert the dependency for Birt Runtime         <dependency>             <groupId>org.eclipse.birt.runtime</groupId>             <artifactId>org.eclipse.birt.runtime</artifactId>  ...