Netbeans Maven Spring and Hibernate project

Create new Netbeans Maven > Web Application project
Add Spring and Hibernate frameworks to the project
Place a persistence.xml in src/main/resources/ folder

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="nameOfPUHere" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>nl.code4all.examtrainer.db.Exam</class>     
        <properties>
            <property name="hibernate.connection.username" value="postgres"/>
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
            <property name="hibernate.connection.password" value="abc"/>
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/dbname"/>
            <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

Add mvc and context to dispatcher-servlet.xml for auto detecting beans and using annotations. Also add a view resolver. This maps your urls to the correct views in the webapp folder.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
    <mvc:annotation-driven/>
 
    <context:component-scan base-package="nl.code4all.examtrainer"/> 
 
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />    
</beans>

Create the annotated Controller:

package nl.code4all.examtrainer.controller;
 
import nl.code4all.examtrainer.db.Exam;
import nl.code4all.examtrainer.util.DatabaseEntityManager;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class ExamController {
 
    @RequestMapping("/exam/add")
    public ModelAndView add() {
        return new ModelAndView("exam", "command", new Exam());
    }
 
    @RequestMapping(value = "/exam/save", method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("exam")
                            Exam exam, BindingResult result) {
 
        if (DatabaseEntityManager.getEntityManager().getTransaction().isActive()) {
            DatabaseEntityManager.getEntityManager().getTransaction().rollback();
            DatabaseEntityManager.getEntityManager().getTransaction().begin();
        } else {
            DatabaseEntityManager.getEntityManager().getTransaction().begin();
        }
 
        DatabaseEntityManager.getEntityManager().persist(exam);
 
        DatabaseEntityManager.getEntityManager().getTransaction().commit();
 
        return new ModelAndView("test");
    }
}

Create the Entity with annotations

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name = "exam")
public class Exam implements java.io.Serializable {
 
    private Integer id;
    private String name;
 
    public Exam() {
    }
 
    public Exam(String name) {
        this.name = name;
    }
 
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    @Column(name = "name", nullable = false, length = 255)
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "Exam [id=" + id + ", name=" + name + "]";
    }
}

Create the Util class to get the Hibernate EntityManager.

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
 
public class DatabaseEntityManager {
 
    static {
        getEntityManager();
    }
 
    public DatabaseEntityManager() {
    }
    private static EntityManagerFactory entityManagerFactory;
    private static EntityManager entityManager;
 
    public static EntityManager getEntityManager() {
 
        if (entityManager == null) {
            try {
                entityManagerFactory = javax.persistence.Persistence.createEntityManagerFactory("nameOfPUHere");
            } catch (java.lang.IllegalStateException ex) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ex1) {
                    Logger.getLogger(DatabaseEntityManager.class.getName()).
                            log(Level.SEVERE, null, ex1);
                }
                getEntityManager();
            }
            entityManager = entityManagerFactory.createEntityManager();
        }
        return entityManager;
    }
 
    public static EntityManagerFactory getEntityManagerFactory() {
        if (entityManagerFactory == null) {
            entityManagerFactory = javax.persistence.Persistence.createEntityManagerFactory("nameOfPUHere");
            entityManager = entityManagerFactory.createEntityManager();
        }
        return entityManagerFactory;
    }
}

Remove the jdbc-stdext 2.0 dependency from the pom.xml

<dependency>
            <groupId>javax.sql</groupId>
            <artifactId>jdbc-stdext</artifactId>
            <version>2.0</version>
        </dependency>

Change the jta dependency version tot 1.1

<dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

Add test.jsp file to in WEB-INF/jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
 
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Test page</title>
    </head>
 
    <body>
        <p>Exam added.</p>
    </body>
</html>

Run the project (F6)

Navigation
Print/export
Toolbox