Maven Spring Hibernate MySQL


I would like to discuss , a sample working program using Maven, Hibernate, Spring ad MySQL
The development IDE is eclipse.
Step 1:

If we do not have Maven plugin, we can download from eclipse Market place. [ Help -> MarketPlace ]

Step 2:

As our objective is to interact with MySQL, we shall create a database with a name [ Eg: raymond]. create a table Item with 3 fields ItemId, ItemCode and ItemName . ItemId is auto increment and Item Code is primary key. We shall create a POJO java class [ in Step 5 ] with getters and setters that corresponds to ItemId, ItemCode and ItemName in the data base table.

Step 3:

Once our IDE is ready, we can create a new maven project using eclipse. Select Maven archetype as : maven-archetype-quickstart. The Artifactid will be the project name. [ Eg; SampleMavenProject ]. The eclipse IDE will generate the folder structure and the main folders is : src/main/java. We can create our packages inside this folder. As a convention we can create separate packages for:

1. App.java,

Create a package for eg: com.myname.SampleMavenProject. Create a java file and name it as App.java. This program would contain ‘public static void main’ function to run our sample application. The aim of the file would be to create an object of POJO class and set its members with values and we can call save , update and delete functions to save the POJO value into database.The code for App.java id:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class App
{
public static void main( String[] args )
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext(“resources/config/BeanLocations.xml”);

}

}

2. Buisness Logic or buisness operations

For our business operations, we can create two packages. (a) for interface that prescribes the functionality (b) for implementing the interface.Eg: com.myname.SampleMavenProject.item.bo and com.myname.SampleMavenProject.item.bo.impl.

Inside the package intended for interface, we can create a java interface file (ItemBo.java) with following code:

import com.myname.SampleMavenProject.item.model.Item;// Location of POJO

public interface ItemBo {

void save(Item item);
void update(Item item);
void delete(Item item);
Item findByItemCode(String itemCode);
}

Inside com.myname.SampleMavenProject.item.bo.impl, create a java file with name: ItemBoImpl.java

public class ItemBoImpl implements ItemBo{

ItemDao itemDao;

public void setItemDao(ItemDao itemDao) {
this.itemDao = itemDao;
}

public void save(Item item){
itemDao.save(item);
}

public void update(Item item){
itemDao.update(item);
}

public void delete(Item item){
itemDao.delete(item);
}

public Item findByItemCode(String itemCode){
return itemDao.findByItemCode(itemCode);
}
}

In this file we have implemented save, update, delete functions and also invoked the data access function and passed the pojo object to it.

3. Data Access Object or Database interaction.

we can create two packages for defining database related operations. Name the packages as com.myname.SampleMavenProject.item.dao and com.myname.SampleMavenProject.item.dao.impl

create a interface inside com.myname.SampleMavenProject.item.dao

import com.myname.SampleMavenProject.item.model.Item;// Location of POJO

public interface ItemDao {

void save(Item item);
void update(Item item);
void delete(Item item);
Item findByItemCode(String itemCode);
}

create implementation file inside the package : com.myname.SampleMavenProject.item.dao.impl

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ItemDaoImpl extends HibernateDaoSupport implements ItemDao{

public void save(Item item){
getHibernateTemplate().save(item);
}

public void update(Item item){
getHibernateTemplate().update(item);
}

public void delete(Item item){
getHibernateTemplate().delete(item);
}

public Item findByItemCode(String itemCode){
List list = getHibernateTemplate().find(
“from Item where itemCode=?”,itemCode
);
return (Item)list.get(0);
}

}

Step 4: creating POJO class

create package : “com.myname.SamplemavenProject.item.model.Item”
import java.io.Serializable;

public class Item implements Serializable {

private static final long serialVersionUID = 1L;

private Long itemId;
private String itemCode;
private String itemName;
public Long getItemId() {
return itemId;
}
public void setItemId(Long itemId) {
this.itemId = itemId;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}

Step 5: resources

Stetting up resources using xml files for Maven. Since this is a ‘maven-archetype-quickstart’ project, we should create a folder/package ‘resources’ in src/main/java. Maven expects xml files to be placed in ‘resources’ folder.

Inside ‘resources’ folder we can create separate packages for different purpose. Let us create config, database, hibernate, properties and spring packages inside ‘resources’.

1. Inside config package, let us create BeanLocations.xml

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd”&gt;

<!– Database Configuration –>
<import resource=”../database/DataSource.xml”/>
<import resource=”../database/Hibernate.xml”/>

<!– Beans Declaration –>
<import resource=”../spring/Item.xml”/>

</beans>

2. Inside database package, create ‘DataSource.xml’

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd”&gt;

<bean
class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>
<property name=”location”>
<value>resources/properties/database.properties</value>
</property>
</bean>

<bean id=”dataSource” destroy-method=”close” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>
<!– class=”org.apache.commons.dbcp.BasicDataSource”>–>

<property name=”driverClassName” value=”${jdbc.driverClassName}” />
<property name=”url” value=”${jdbc.url}” />
<property name=”username” value=”${jdbc.username}” />
<property name=”password” value=”${jdbc.password}” />

<!– <property name=”defaultAutoCommit” value=”true” /> –>
</bean>

</beans>

3. Inside database package, create ‘Hibernate.xml’

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd”&gt;

<!– Hibernate session factory –>
<bean id=”sessionFactory”
class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>

<property name=”dataSource”>
<ref bean=”dataSource”/>
</property>

<!– org.hibernate.dialect.MySQLDialect –>
<property name=”hibernateProperties”>
<props>
<prop key=”hibernate.dialect”>org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key=”hibernate.show_sql”>true</prop>
<prop key=”hibernate.connection.autocommit”>false</prop>
<prop key=”hibernate.transaction.factory_class”>
org.hibernate.transaction.JDBCTransactionFactory
</prop>

</props>
</property>

<property name=”mappingResources”>
<list>
<value>resources/hibernate/Item.hbm.xml</value>
</list>
</property>

</bean>
</beans>

Now we have defined the database connection parameters in DataSource.xml and Hibernate properties in Hibernate.xml. In Hibernate.xml, we define the dialect with database. Since our data base is MySQL, we have used org.hibernate.dialect.MySQL5InnoDBDialect. properties like auto commit is handled here. Regarding MySQL database, auto commit in Hibernate.xml does not have any implications (pertaining to my knowledge).

4. create hibernate package and inside the package create Item.hbm.xml file.

In this file we define the database structure.

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”&gt;

<hibernate-mapping>
<class name=”com.myname.SampleMavenProject.item.model.Item” table=”item” catalog=”raymond”>
<id name=”itemId” type=”java.lang.Long”>
<column name=”ITEM_ID” />
<generator class=”identity” />
</id>
<property name=”itemCode” type=”string”>
<column name=”ITEM_CODE” length=”10″ not-null=”true” unique=”true” />
</property>
<property name=”itemName” type=”string”>
<column name=”ITEM_NAME” length=”20″ not-null=”true” unique=”true” />
</property>
</class>
</hibernate-mapping>

We have now mapped the database table item inside the database ‘raymond’ to hibernate.

5. create ‘properties’ package inside resources. create database.properties file in the package.

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/raymond
jdbc.username=raymond
jdbc.password=raymond

We have defined the connection Url, Driver class, username and password. It is better we create a new user in database with all necessary privilages. For this example, I have create a new user with user name as ‘raymond’ and password also as ‘raymond’

6. Create spring package inside resources. Add spring.xml file to it.

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd”&gt;

<!– Item business object –>
<bean id=”itemBo” class=”com.myname.SamplemavenProject.item.bo.impl.ItemBoImpl” >
<property name=”itemDao” ref=”itemDao” />
</bean>

<!– Item Data Access Object –>
<bean id=”itemDao”.myname.SamplemavenProject.item.dao.impl.ItemDaoImpl” >
<property name=”sessionFactory” ref=”sessionFactory”></property>
</bean>

</beans>

In this file we mention the bean id to spring frame work for auto wiring facility. The java business class and its corresponding data access object class are defined. The session factory property is also defined.

Step 6: External dependencies

Now we are almost complete with eclipse IDE, please check if you have

apache-maven-2.2.1

if not download one and place it in a drive [ Eg:C:\apache-maven-2.2.1 ]

In Windows O.S, create the following Environment variables:

1. M2_HOME

C:\apache-maven-2.2.1

2. M2

%M2_HOME%\bin

3. Path

%M2%;

Now we can execute Maven from command line.

Step 7. Run the application

In eclipse project, in Run Configuration, add/set Maven Runtime as Eg:C:\apache-maven-2.2.1

Now to download the dependency jar files for the project, we should define pom.xml

Some of the dependencies that , i have mentioned is extra ( may be useful in future examples)

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>

<groupId>com.myname</groupId>
<artifactId>SampleMavenProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Maven3</name>
<url>http://maven.apache.org</url&gt;

<repositories>
<repository>
<id>spring-milestone</id>
<name>Spring Portfolio Milestone Repository</name>
<url> http://s3.amazonaws.com/maven.springframework.org/milestone
</url>
</repository>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url> https://maven2-repository.dev.java.net/nonav/repository</url&gt;
</repository>

</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
</dependency>
<!– Spring framework –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<!– Spring AOP dependency –>
<!– <dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency> –>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2.2</version>
</dependency>
<!– MySQL database driver –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>

<!– Hibernate framework –>
<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.3.GA</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.4.GA</version>

</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.2</version>
</dependency>

<!– Hibernate library dependecy start –>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>

<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>

<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager
</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.0.beta9a</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp-provider</artifactId>
<version>0.7.1.RELEASE</version>
</dependency>
<!– Hibernate library dependecy end –>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

</dependencies>

</project>

Now the program is ready to run and we can execute, the App.java.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s