Hibernate4 + spring4 + maven example

Here is an example using hibernate4, spring4 and maven. I have described how you can do simple create, read, update and delete operations using hibernate.  I have used hibernate annotations for this example.

Download source code -> Hibernate4 example source code (2175)

directory structure

hibernate example directory structure

Maven Configuration

<?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.mycuteblog</groupId>
    <artifactId>hibernate4</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <spring.version>4.0.6.RELEASE</spring.version>
        <hibernate.version>4.3.6.Final</hibernate.version>
        <mysql.version>5.1.6</mysql.version>
    </properties>

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

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

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

    </dependencies>

    <!--additional configurations to run project standalone-->
</project>

 

User Class

This class contains all required fields for the users table. Hibernate will create users table automatically using these fields.

@Entity
@Table(name = "users")
public class User {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    @Column(name = "user_id")
    private long userId;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "age")
    private int age;
    @Column(name = "created_date")
    private Date createdDate;

   <-- getters and setters -->
}

 

Hibernate session factory class

This class is used to get current session from the session factory. Session factory is injected through spring.

public class HibernateSessionFactoryImpl implements HibernateSessionFactory {

    private SessionFactory sessionFactory;

    @Override
    public Session getSession() {
        return this.sessionFactory.getCurrentSession();
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}

 

User dao

This class contains all CRUD operations for user class.

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    HibernateSessionFactory hibernateSessionFactory;

    @Override
    public boolean addUser(User user) {
        Session session = hibernateSessionFactory.getSession();
        session.save(user);
        return true;
    }

    @Override
    public User getUser(long userId) {
        Session session = hibernateSessionFactory.getSession();
        User user = (User) session.createCriteria(User.class)
                .add(Restrictions.eq("userId", userId))
                .uniqueResult();

        return user;
    }

    @Override
    public boolean updateUser(User user) {
        Session session = hibernateSessionFactory.getSession();
        session.update(user);
        return true;
    }

    @Override
    public boolean deleteUser(User user) {
        Session session = hibernateSessionFactory.getSession();
        session.delete(user);
        return true;
    }
}

 

User Controller

This class handles data using dao class. You can implement your business logic here.

@Transactional
public class UserControllerImpl implements UserController {

    @Autowired
    private UserDao userDao;

    @Override
    public boolean addUser(User user) {
        return userDao.addUser(user);
    }

    @Override
    public User getUser(long userId) {
        return userDao.getUser(userId);
    }

    @Override
    public boolean updateUser(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public boolean deleteUser(User user) {
        return userDao.deleteUser(user);
    }
}

 

Hibernate configuration

This file contains all required hibernate configurations. I have used cp30 for data pooling.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
  
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

    <bean id="dataSource"
          class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hibernate_example?autoReconnect=true"/>
        <property name="user" value="user"/>
        <property name="password" value="password"/>

        <!-- C3P0 properties  refer: http://www.mchange.com/projects/c3p0/ -->
        <property name="acquireIncrement" value="2"/>
        <property name="minPoolSize" value="20"/>
        <property name="maxPoolSize" value="50"/>
        <property name="maxIdleTime" value="600"/>
    </bean>

    <!-- Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource"/>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <property name="packagesToScan" value="com.mycuteblog.hibernate4"/>
    </bean>

    <bean id="hibernateSessionFactory" class="com.mycuteblog.hibernate4.dao.impl.HibernateSessionFactoryImpl">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

spring configuration

<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"
       xsi:schemaLocation="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.xsd">

    <context:component-scan base-package="com.mycuteblog.hibernate4" />

    <context:annotation-config />

    <import resource="classpath:hibernate-config.xml" />

    <bean name="userController" class="com.mycuteblog.hibernate4.controller.impl.UserControllerImpl" />

</beans>

Here is the main class which tests all we created above.

public class HibernateDemo {

    public static void main(String[] args){

        ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml");

        UserController userController = (UserController) context.getBean("userController");

        User user = new User();
        user.setUserId(100);
        user.setFirstName("Foo");
        user.setLastName("Boo");
        user.setAge(25);
        user.setCreatedDate(new Date());

        userController.addUser(user);

        User savedUser = userController.getUser(100);
        System.out.println(savedUser.toString());

        user.setFirstName("Boo");
        user.setLastName("Foo");
        user.setAge(24);
        userController.updateUser(user);

        User updatedUser = userController.getUser(100);
        System.out.println(updatedUser.toString());

        userController.deleteUser(updatedUser);

        User deletedUser = userController.getUser(100);

        if (deletedUser == null){
            System.out.println("user has been deleted from db");
        }

    }
}

Here is the output

User{id=1, userId=100, firstName='Foo', lastName='Boo', age=25, createdDate=2014-08-19 22:26:55.0}
User{id=1, userId=100, firstName='Boo', lastName='Foo', age=24, createdDate=2014-08-19 22:26:55.0}
user has been deleted from db

Download source code -> Hibernate4 example source code (2175)

Enjoyed this article? Share with friends

Subscribe

Subscribe to our email feed and never miss a post

Join Us