girlcoderuk











{July 14, 2013}   Configuring Hibernate and Spring for Standalone Application

This article is designed to fill a gaping hole in the Examples for Spring / Hibernate configuration and that is for Standalone Applications.

Usually all the demonstrations are for Web applications or J2EE applications, so this one is for a simple Command Line Application. I use Intellij Idea and Maven but i hope it works as easily if you are using Netbeans or Eclipse.

Ok Lets start out Easily:

Create a new Maven Project with no Archetype

<?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>com.github.theresajayne.standaloneexample</groupId>
<artifactId>standaloneExample</artifactId>
<version>1.0-SNAPSHOT</version>
</project>

Idea will have created the pom file but nothing else do under src/main/java add a package for your system (mine is com.github.theresajayne/standaloneexample) and create a main class under there to match your project name

package com.github.theresajayne.standaloneexample;

public class StandaloneExample {
}

now lets return to the pom file, We need to add the Spring, Hibernate and MySQL libraries to the project and then rebuild to make it download all the dependencies. This is a simple copy/paste task so my complete pom file is below.

<?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>com.github.theresajayne.standaloneexample</groupId>
<artifactId>standaloneExample</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<spring.version>3.2.3.RELEASE</spring.version>
<hibernate.version>4.2.2.Final</hibernate.version>
</properties>

<dependencies>
<!– Spring –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>

<!– Hibernate –>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>

<!– Others –>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>

</dependencies>

</project>

Now we have the project building lets add some configuration files.

under src/main/resources we need to make the spring configuration  file. So create spring-config.xml

<?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:context=”http://www.springframework.org/schema/context” xmlns:tx=”http://www.springframework.org/schema/tx”
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd “>
<context:annotation-config/>
<context:component-scan base-package=”com.github.theresajayne.standaloneexample”/>

<!– JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with
username root and root as password. Change below if it’s not the case –>
<bean id=”myDataSource” class=”org.apache.commons.dbcp.BasicDataSource” destroy-method=”close”>
<property name=”driverClassName” value=”com.mysql.jdbc.Driver”/>
<property name=”url” value=”jdbc:mysql://localhost:3306/standalone”/>
<property name=”username” value=”root”/>
<property name=”password” value=”root”/>
<property name=”validationQuery” value=”SELECT 1″/>
</bean>

<!– Hibernate Session Factory –>
<bean id=”mySessionFactory” class=”org.springframework.orm.hibernate4.LocalSessionFactoryBean”>
<property name=”dataSource” ref=”myDataSource”/>
<property name=”packagesToScan”>
<array>
<value>com.github.theresajayne.standaloneexample</value>
</array>
</property>
<property name=”hibernateProperties”>
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>

<!– Hibernate Transaction Manager –>
<bean id=”transactionManager” class=”org.springframework.orm.hibernate4.HibernateTransactionManager”>
<property name=”sessionFactory” ref=”mySessionFactory”/>
</bean>

<!– Activates annotation based transaction management –>
<tx:annotation-driven transaction-manager=”transactionManager”/>

</beans>

This now is all we need on configuration boilerplate code as the rest is all done via annotations.

Now back to the Main class of the application. We start off the file looking like this

package com.github.theresajayne.standaloneexample;

public class StandaloneExample {

public static void main(final String[] args) throws Exception {

}
}

First we need to annotate the whole class with @Component This as you will see will allow us to create the main class using Spring, next we add the main code providing us with the following

package com.github.theresajayne.standaloneexample;

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

@Component
public class StandaloneExample {

public static void main(final String[] args) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext(“spring-config.xml”);
StandaloneExample standalone = ctx.getBean(StandaloneExample.class);
standalone.startStandalone();
}
}

If you are using an IDE you will see the startStandalone() method is currently Red meaning that it is not there, so if you can use your ide tools to create it.

Next we will create the Dao and allow it to create a table in the preexisting standalone schema in the database (if you have not created the schema then you will need to.

Under the standaloneexample package create a new package called model.beans, then create StandaloneVO inside. Annotate the class as @Entity and @Table(name=”standalone”) within the class add and id with the @Id and @GeneratedValue annotations then add any other fields you wish on your object.remember to make them private with public getters and setters.

package com.github.theresajayne.standaloneexample.model.beans;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;

@Entity
@Table(name=”standalone”)
public class StandaloneVO {

@Id
@GeneratedValue
private long id;
private String name;
private double amount;
private Date created;

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

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

public double getAmount() {
return amount;
}

public void setAmount(double amount) {
this.amount = amount;
}

public Date getCreated() {
return created;
}

public void setCreated(Date created) {
this.created = created;
}
}

Now add a new package under model called dao, DAO means Data Access Object and these are the methods to execute the CRUD methods (Create Read Update and Delete) , normally you would also have a service layer which would take the VO (value objects) and change them to DTO’s or FBs (Data Transfer Objects or FormBeans) This is a good approach to seperate Database Objects from transient data movement objects so you do not inadvertently alter a record you only wanted to modify on the front end. but as this is an example we will go straight to the DAO layer.

First create an interface StandaloneDao

package com.github.theresajayne.standaloneexample.model.dao;

import com.github.theresajayne.standaloneexample.model.beans.StandaloneVO;

import java.util.List;

public interface StandaloneDao {
public List<StandaloneVO> findAll();

void save(StandaloneVO standaloneVO);
}

Now create the Implementation of the Dao usually called StandaloneDaoImpl

package com.github.theresajayne.standaloneexample.model.dao;

import com.github.theresajayne.standaloneexample.model.beans.StandaloneVO;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
@Transactional
public class StandaloneDaoImpl implements StandaloneDao {

@Autowired
private SessionFactory sessionFactory;

@Override
public List<StandaloneVO> findAll() {
Session session = sessionFactory.getCurrentSession();
return (List<StandaloneVO>)session.createQuery(“from StandaloneVO”).list();
}

@Override
public void save(StandaloneVO standaloneVO) {
Session session = sessionFactory.getCurrentSession();
session.save(standaloneVO);
}
}

Now lets do something with our code….

private void startStandalone() {
StandaloneVO standaloneVO = new StandaloneVO();
standaloneVO.setName(“Test1″);
standaloneVO.setAmount(239.32);
standaloneVO.setCreated(new Date());
standaloneDao.save(standaloneVO);
List<StandaloneVO> result = standaloneDao.findAll();
for(StandaloneVO vo : result)
{
System.out.println(vo.getId()+”:”+vo.getName()+”:”+vo.getAmount()+”:”+vo.getCreated());
}

}

Now each time you run the code there will be a new line to the output….

1:Test1:239.32:2013-07-14 13:22:11.0
2:Test1:239.32:2013-07-14 13:22:21.0

Process finished with exit code 0

Hopefully this article has helped to make setting up Spring and Hibernate easy for Stand Alone Applications.

Source code is available from http://www.github.com/theresajayne/standaloneexample



David says:

I can’t believe it… It worked with an app-fuse modular application!! Thanks



Arturo says:

hi, i’m following the same pattern for a swing application, but I have this problem; if the standalone app is executed in more than one pc at the same time against the same database instance, ¿how could we keep the different sessions synchronized? The sessionFactory is the owner and we cannot control when to open or close it, ¿How can we refresh the entire model to keep it synchronized? thanks



Well, the question is are you using cache and when do you get the information? You would need to use no cache and re-get the data on a regular basis. There will obviously be some small delay in data synching unless you had the programs connect to a listener and be notified of a data change



Amrit Lutchman says:

I Had to change the line in spring config: to

And then it worked like a charm. A smart peace of code.



Amrit Lutchman says:

<context:component-scan base-package=”com.github.theresajayne.standaloneexample”/> to <context:component-scan base-package=”com.github.theresajayne”/>

Sorry forgot HTML tag…



Leave a comment

et cetera