Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

A project using NetBeans 7, JUnit, Maven, HSQLDB, Spring and Hibernate

DZone's Guide to

A project using NetBeans 7, JUnit, Maven, HSQLDB, Spring and Hibernate

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

I was reading a blog article the other day and decided to try the code out myself, however, I wanted to do it my way so I changed several things along the way. This article will outline what I did to get NetBeans 7 working with Spring, Hibernate, HSQLDB, JUnit and Maven all working together. The original code for the original article can be found here.

I began my project by creating a new Maven project called: SimpleSpringHibernate.

I added the following dependencies:

Note: Keep in mind you only really need to add Hibernate, Spring Framework, JUnit, HSQLDB, and the rest will be pulled in by Maven. I’ve included the above screen shot though just to to show everything as I had it configured.

I created just one entity called Employee which takes an id, name and a department. It is wired up for Hibernate and fairly simple to understand.

Employee.java

package com.giantflyingsaucer.simplespringhibernate.entity;
 
import javax.persistence.*;
import java.io.Serializable;
import org.hibernate.annotations.GenericGenerator;
 
@Entity
@Table(name = "Employees")
public class Employee implements Serializable {
 
    private String employeeId;
    private String name;
    private String department;
 
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(name = "EmployeeId", nullable=false)
    public String getEmployeeId() {
        return this.employeeId;
    }
 
    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }
    @Column(name = "Name", nullable=false)
    public String getEmployeeName() {
        return this.name;
    }
 
    public void setEmployeeName(String name) {
        this.name = name;
    }
    @Column(name = "Department", nullable=false)
    public String getEmployeeDepartment() {
        return this.department;
    }
 
    public void setEmployeeDepartment(String department) {
        this.department = department;
    }
}

After that and according to the original article I built the interface for the EmployeeDAO.

EmployeeDAO.java

package com.giantflyingsaucer.simplespringhibernate.dao;
 
import java.util.List;
import com.giantflyingsaucer.simplespringhibernate.entity.Employee;
 
public interface EmployeeDAO {
    public void saveEmployee(Employee employee);
    public List<Employee> getAllEmployees(Employee employee);
    public Employee getEmployeeById(String employeeId);
    public void deleteEmployee(Employee employee);
}

The actual implementation code looks like this:

EmployeeDAOImpl.java

package com.giantflyingsaucer.simplespringhibernate.dao;
 
import com.giantflyingsaucer.simplespringhibernate.entity.Employee;
 
import java.util.List;
 
import org.hibernate.SessionFactory;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
 
@Repository("EmployeeDAO")
@Transactional
public class EmployeeDAOImpl implements EmployeeDAO {
    private HibernateTemplate hibernateTemplate;
 
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        hibernateTemplate = new HibernateTemplate(sessionFactory);
    }
 
    @Transactional(readOnly = false)
    public void saveEmployee(Employee employee) {
        hibernateTemplate.saveOrUpdate(employee);
    }
 
    @Transactional(readOnly = false)
    public void deleteEmployee(Employee employee) {
        hibernateTemplate.delete(employee);
    }
 
    @SuppressWarnings("unchecked")
    public List<Employee> getAllEmployees(Employee employee) {
        return (List<Employee>) hibernateTemplate.find("from "
                + Employee.class.getName());
    }
 
    public Employee getEmployeeById(String employeeId) {
        return hibernateTemplate.get(Employee.class, employeeId);
    }
}

My JUnit test code looks like this:

EmployeeTest.java

package com.giantflyingsaucer.simplespringhibernate;
 
import java.util.List;
 
import org.junit.Test;
import org.junit.Assert;
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 com.giantflyingsaucer.simplespringhibernate.dao.*;
import com.giantflyingsaucer.simplespringhibernate.entity.Employee;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( { "/app-config.xml" })
public class EmployeeTest {
    private EmployeeDAO dao;
 
    @Autowired
    public void setDao(EmployeeDAO dao) {
        this.dao = dao;
    }
 
    @Test
    public void testCreateData() {
        int expectedResult = 1;
        Employee employee = new Employee();
        employee.setEmployeeDepartment("Human Resources");
        employee.setEmployeeName("Barry Jones");
        dao.saveEmployee(employee);
        Assert.assertEquals(expectedResult, dao.getAllEmployees(new Employee()).size());
    }
 
    @Test
    public void testRetrieveData() {
        List<Employee> employeeList = dao.getAllEmployees(new Employee());
        Assert.assertEquals(1, employeeList.size());
        Employee employeeExpected = employeeList.get(0);
        Employee employeeResult = dao.getEmployeeById(employeeExpected.getEmployeeId());
        Assert.assertEquals(employeeExpected.getEmployeeId(), employeeResult.getEmployeeId());
    }
 
    @Test
    public void testUpdateData() {
        List<Employee> employeeList = dao.getAllEmployees(new Employee());
        Assert.assertEquals(1, employeeList.size());
        Employee employeeExpected = employeeList.get(0);
        employeeExpected.setEmployeeName("Jim Jones");
        dao.saveEmployee(employeeExpected);
        Employee employeeResult = dao.getEmployeeById(employeeExpected.getEmployeeId());
        Assert.assertEquals(employeeExpected.getEmployeeName(), employeeResult
                .getEmployeeName());
    }
 
    @Test
    public void testDeleteData() {
        List<Employee> employeeList = dao.getAllEmployees(new Employee());
        Assert.assertEquals(1, employeeList.size());
        Employee employeeExpected = employeeList.get(0);
        dao.deleteEmployee(employeeExpected);
        Employee employeeResult = dao.getEmployeeById(employeeExpected.getEmployeeId());
        Assert.assertEquals(employeeResult, null);
    }
}

All that’s left is three configuration files needed mostly by Spring. These files go into the resources folder.

app-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"
    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-3.0.xsd">
 
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>/configuration.properties</value>
            </list>
        </property>
    </bean>
 
    <context:component-scan base-package="com.giantflyingsaucer.simplespringhibernate" />
    <import resource="db-config.xml" />
</beans>

db-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:p="http://www.springframework.org/schema/p"
    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.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        destroy-method="close">
 
        <property name="driverClass">
            <value>${jdbc.driver.className}</value>
        </property>
        <property name="jdbcUrl">
            <value>${jdbc.url}</value>
        </property>
        <property name="user">
            <value>${jdbc.username}</value>
        </property>
        <property name="password">
            <value>${jdbc.password}</value>
        </property>
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="packagesToScan" value="com.giantflyingsaucer.simplespringhibernate.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <tx:annotation-driven />
</beans>

Note: I’m using HSQLDB here but you could swap that out for any of the Hibernate supported databases.

configuration.properties

jdbc.driver.className=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:file:consoledb;shutdown=true
jdbc.username=sa
jdbc.password=
jdbc.hibernate.dialect=org.hibernate.dialect.HSQLDialect

My project layout looks like this:

Clean and build the project and all four tests should pass.

You can find the project files here.

 

From http://www.giantflyingsaucer.com/blog/?p=2934#more-2934

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}