Home > Hibernate, J2EE, XML > Maven 3 + Hibernate 3.2 + MySQL Example (XML Mapping)

Maven 3 + Hibernate 3.2 + MySQL Example (XML Mapping)

Hibernate is a popular open source ORM framework which is frequently used with java.

Here is the list of technologies which are gonna used.

  • Maven 3
  • JDK 1.6
  • Hibernate 3.2
  • MySql 5

First we have create a table for ORM. Here is the MySql script for this

DROP TABLE IF EXISTS `stock`;
CREATE TABLE `stock` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` VARCHAR(10) NOT NULL,
  `STOCK_NAME` VARCHAR(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Create a sample project using Maven. Use archetype as quick-start. Then add the following dependencies to the pom.xml


<!-- MySQL database driver -->
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>5.1.21</version>
</dependency>

 <!-- Hibernate framework -->
 <dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version>4.1.7.Final</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>cglib</groupId>
 <artifactId>cglib</artifactId>
 <version>2.2</version>
 </dependency>
 <!-- Hibernate library dependecy end -->

Here is the project structure.

hbn1

Now create Stock class as follows.


package com.supun.common;

/**
 * Model class for Stock
 */
public class Stock implements java.io.Serializable{

/**
 *
 */
 private static final long serialVersionUID = 1L;

 private Integer stockId;
 private String stockCode;
 private String stockName;

 public Stock (){

 }

public Stock(String stockCode, String stockName){
 this.stockCode = stockCode;
 this.stockName = stockName;
 }

public Integer getStockId() {
 return stockId;
 }
 public void setStockId(Integer stockId) {
 this.stockId = stockId;
 }
 public String getStockCode() {
 return stockCode;
 }
 public void setStockCode(String stockCode) {
 this.stockCode = stockCode;
 }
 public String getStockName() {
 return stockName;
 }
 public void setStockName(String stockName) {
 this.stockName = stockName;
 }

}

Now add HibernateUtil class.


package com.supun.persistence;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

@SuppressWarnings("deprecation")
 private static SessionFactory buildSessionFactory() {
 try {
 // Create the SessionFactory from hibernate.cfg.xml
 return new Configuration().configure().buildSessionFactory();
 }
 catch (Throwable ex) {
 // Make sure you log the exception, as it might be swallowed
 System.err.println("Initial SessionFactory creation failed." + ex);
 throw new ExceptionInInitializerError(ex);
 }
 }

public static SessionFactory getSessionFactory() {
 return sessionFactory;
 }

 public static void shutdown() {
 // Close caches and connection pools
 getSessionFactory().close();
 }
}

Here is App.java class


package com.supun.common;

import org.hibernate.Session;

import com.supun.common.Stock;
import com.supun.persistence.HibernateUtil;

/**
 * Hello world!
 *
 */
public class App
{
 public static void main( String[] args )
 {
 System.out.println("Maven + Hibernate + MySQL");
 Session session = HibernateUtil.getSessionFactory().openSession();

 session.beginTransaction();
 Stock stock = new Stock();

 stock.setStockCode("4715");
 stock.setStockName("GENM");

 session.save(stock);
 session.getTransaction().commit();
 }
}

Then add the configuration files as follows.

Stock.hbm.xml


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.supun.common.Stock" table="stock" catalog="technodyne">
 <id name="stockId" type="java.lang.Integer">
 <column name="STOCK_ID" />
 <generator class="identity" />
 </id>
 <property name="stockCode" type="string">
 <column name="STOCK_CODE" length="10" not-null="true" unique="true" />
 </property>
 <property name="stockName" type="string">
 <column name="STOCK_NAME" length="20" not-null="true" unique="true" />
 </property>
 </class>
</hibernate-mapping>

Then add hibernate.cfg.xml


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
 <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="hibernate.connection.password"></property>
 <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/technodyne</property>
 <property name="hibernate.connection.username">root</property>
 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
 <property name="show_sql">true</property>
 <mapping resource="com/supun/common/Stock.hbm.xml"></mapping>
 </session-factory>
</hibernate-configuration>

Now run the application.

You can see the following

Hibernate: insert into technodyne.stock (STOCK_CODE, STOCK_NAME) values (?, ?)

Advertisements
Categories: Hibernate, J2EE, XML
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: