Hibernate with XML configuration in a Web Application Example!

Just a Hello World!

This is my Database:
Korays-MacBook-Pro:Development koraytugay$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 259
Server version: 5.5.44 MySQL Community Server (GPL)
 
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
 
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
 
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
 
mysql> use sakila;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
 
Database changed
mysql> describe actor;
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| Field       | Type                 | Null | Key | Default           | Extra                       |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| actor_id    | smallint(5) unsigned | NO   | PRI | NULL              | auto_increment              |
| first_name  | varchar(45)          | NO   |     | NULL              |                             |
| last_name   | varchar(45)          | NO   | MUL | NULL              |                             |
| last_update | timestamp            | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
4 rows in set (0.00 sec)

Ok as usual lets start with pom.xml:
<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/maven-v4_0_0.xsd">
 
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>biz.tugay.saqila</groupId>
    <artifactId>saqila</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
 
    <name>saqila Maven Webapp</name>
 
    <dependencies>
 
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
 
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
 
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
            <version>2.2</version>
        </dependency>
 
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
            <scope>provided</scope>
        </dependency>
 
        <!-- hibernate here -->
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.10.Final</version>
        </dependency>
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.10.Final</version>
        </dependency>
 
    </dependencies>
 
    <build>
        <finalName>saqila</finalName>
    </build>
</project>

and web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                             http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
         version="3.0">
</web-app>

we have 2 configuration files for Hibernate, hibernate.cfg.xml and Actor.hbm.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.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sakila</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"/>
        <property name="current_session_context_class">thread</property>
        <property name="hibernate.show_sql">false</property>
        <mapping resource="Actor.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
    <class name="biz.tugay.saqila.model.Actor" table="actor">
        <id name="actor_id" type="int" column="actor_id">
            <generator class="native"/>
        </id>
        <property name="first_name" column="first_name" type="string"/>
        <property name="last_name" column="last_name" type="string"/>
    </class>
</hibernate-mapping>

and our Actor and WelcomeServlet classes:
package biz.tugay.saqila.model;
/* User: koray@tugay.biz Date: 06/08/15 Time: 17:03 */
 
public class Actor {
 
    private int actor_id;
    private String first_name;
    private String last_name;
 
    public int getActor_id() {
        return actor_id;
    }
 
    public void setActor_id(int actor_id) {
        this.actor_id = actor_id;
    }
 
    public String getFirst_name() {
        return first_name;
    }
 
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
 
    public String getLast_name() {
        return last_name;
    }
 
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
 
    @Override
    public String toString() {
        return "Actor{" +
                "actor_id=" + actor_id +
                ", first_name='" + first_name + '\'' +
                ", last_name='" + last_name + '\'' +
                '}';
    }
}
 
package biz.tugay.saqila.servlet;
/* User: koray@tugay.biz Date: 06/08/15 Time: 17:10 */
 
import biz.tugay.saqila.model.Actor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
 
@SuppressWarnings("unchecked")
@WebServlet(urlPatterns = "/")
public class WelcomeServlet extends HttpServlet {
 
    private SessionFactory sessionFactory;
 
    @Override
    public void init() throws ServletException {
        super.init();
        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    }
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
 
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        List<Actor> actors = session.createQuery("FROM Actor").list();
        session.close();
 
        req.setAttribute("actors", actors);
        req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req, resp);
    }
 
    @Override
    public void destroy() {
        sessionFactory.close();
        super.destroy();
    }
}

and finally hello.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
 
<div>
    <p>
        <%--@elvariable id="actors" type="java.util.List<biz.tugay.saqila.model.Actor>"--%>
        <c:forEach items="${actors}" var="actor">
            <c:out value="${actor.first_name}"/> &nbsp; <c:out value="${actor.last_name}" />
            <br />
        </c:forEach>
    </p>
</div>
</body>
</html>

Lets build with maven:
Korays-MacBook-Pro:saqila koraytugay$ mvn clean install
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building saqila Maven Webapp 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ saqila ---
[INFO] Deleting /Users/koraytugay/Development/saqila/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ saqila ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 2 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ saqila ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 2 source files to /Users/koraytugay/Development/saqila/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ saqila ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /Users/koraytugay/Development/saqila/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ saqila ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ saqila ---
[INFO] No tests to run.
[INFO] 
[INFO] --- maven-war-plugin:2.2:war (default-war) @ saqila ---
[INFO] Packaging webapp
[INFO] Assembling webapp [saqila] in [/Users/koraytugay/Development/saqila/target/saqila]
[INFO] Processing war project
[INFO] Copying webapp resources [/Users/koraytugay/Development/saqila/src/main/webapp]
[INFO] Webapp assembled in [91 msecs]
[INFO] Building war: /Users/koraytugay/Development/saqila/target/saqila.war
[INFO] WEB-INF/web.xml already added, skipping
[INFO] 
[INFO] --- maven-install-plugin:2.4:install (default-install) @ saqila ---
[INFO] Installing /Users/koraytugay/Development/saqila/target/saqila.war to /Users/koraytugay/.m2/repository/biz/tugay/saqila/saqila/1.0-SNAPSHOT/saqila-1.0-SNAPSHOT.war
[INFO] Installing /Users/koraytugay/Development/saqila/pom.xml to /Users/koraytugay/.m2/repository/biz/tugay/saqila/saqila/1.0-SNAPSHOT/saqila-1.0-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.060 s
[INFO] Finished at: 2015-08-06T18:19:03+03:00
[INFO] Final Memory: 19M/244M
[INFO] ------------------------------------------------------------------------
Korays-MacBook-Pro:saqila koraytugay$ 

Now we have a file called saqila.war, lets copy it to webapps folder of our Tomcat and start Tomcat.
Korays-MacBook-Pro:bin koraytugay$ ./startup.sh
Using CATALINA_BASE:   /Users/koraytugay/Tools/apache-tomcat-7.0.62
Using CATALINA_HOME:   /Users/koraytugay/Tools/apache-tomcat-7.0.62
Using CATALINA_TMPDIR: /Users/koraytugay/Tools/apache-tomcat-7.0.62/temp
Using JRE_HOME:        /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home
Using CLASSPATH:       /Users/koraytugay/Tools/apache-tomcat-7.0.62/bin/bootstrap.jar:/Users/koraytugay/Tools/apache-tomcat-7.0.62/bin/tomcat-juli.jar
Tomcat started.
Korays-MacBook-Pro:bin koraytugay$ 

Time to hit localhost:8080/saqila

Great!!! Everything is working as expected. Lets shut down Tomcat.
Korays-MacBook-Pro:bin koraytugay$ ./shutdown.sh
Using CATALINA_BASE:   /Users/koraytugay/Tools/apache-tomcat-7.0.62
Using CATALINA_HOME:   /Users/koraytugay/Tools/apache-tomcat-7.0.62
Using CATALINA_TMPDIR: /Users/koraytugay/Tools/apache-tomcat-7.0.62/temp
Using JRE_HOME:        /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home
Using CLASSPATH:       /Users/koraytugay/Tools/apache-tomcat-7.0.62/bin/bootstrap.jar:/Users/koraytugay/Tools/apache-tomcat-7.0.62/bin/tomcat-juli.jar
Korays-MacBook-Pro:bin koraytugay$ 

All seems fine!