How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #3

This is the third in a series of articles, the previous part is available here: How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #2

CREATION OF THE MODEL: THE USER CLASS
We continue the creation of our simple web application and we see in this third part how to add to our project the interaction with a relational database on which users we create will be saved.
Let’s start with the design of our “user” objects and then we create the User class that will contain information that define our users that, for simplicity, we represent at the moment only with full name and country, as well as a unique id with which they will be saved in the database.
The code for the User class will be as follows:

package com.dede.app1st.model;

public class User {

	private int id;
	private String firstname;
	private String lastname;
	private String country;

	public User(String fn, String ln, String country) {
		firstname = fn;
		lastname = ln;
		this.country = country;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}
}

CREATE THE DATABASE
Once we have identified the attributes that represent our users, defining the User class, we have to create a database and a table where users created are stored. To do this we use PostgreSQL as a relational database.
We open its administrative tool, called pgAdmin and on our installation of PostgreSQL we create a new database that we call “firstapp”. In the “firstapp” database we create our table “users” which will contain four columns corresponding to the attributes previously defined in the User class:

  • id
  • firstname
  • lastname
  • country

To create this table click on the icon SQL statement execution icon
that opens the editor to manually insert SQL statements and insert the following SQL script:

CREATE TABLE users {
	user_id SERIAL PRIMARY KEY,
	firstname VARCHAR(40) NOT NULL,
	lastname  VARCHAR(40) NOT NULL,
	country   VARCHAR(40)
}

Click on the “Run” button (green triangle) to actually run the statement and if everything went right we should see a message that communicates us the successful creation of the table.
The following picture summarizes the steps for creating the table described above.

Create Table statement PgAdmin

INTRODUCING JPA SPECIFICATION AND HIBERNATE
To manage data saved into the database through the classic CRUD operations (Create, Read, Update, Delete) we use Hibernate, a framework that provides us with the so-called ORM, Object-Relational Mapping feature. Hibernate indeed is an implementation of the JPA, Java Persistence API specification, that is part of the Java EE platform and essentially it allows us to map our Java objects with our database tables and simplifies activities necessary to ensure data persistence, and access to them.
To use it we have to include her in the project libraries. We go to http://hibernate.org/orm/downloads/ and we download the latest version, at the time of writing this post is the 4.3.6
Unpack the downloaded zip and copy all the jar files in the lib/required folder under the folder WebContent/lib of our project.

Librerie Hibernate nel progetto Eclipse

MAPPING BETWEEN JAVA OBJECTS AND TABLES
Now that we’ve added Hibernate to our project we can proceed with the mapping between our User class and the “users” table we created in PosgreSQL database. To do this we must use a set of annotations provided by the JPA specification to indicate on which table is to be mapped a class and, for each instance variable, which is the corresponding column in the database table.
Annotations of the JPA specification that we use are:

  • @Entity
    • It is used to indicate that a certain class is an entity and it will be mapped with a corresponding table of the database
  • @Table
    • It is used to indicate on which database table it must be mapped the annotated class. By default it is assumed that the database table has the same name of the annotated Java class. In case that the class name and the table name are different, it’s necessary to set the annotation attribute “name” with the name of the table.
      In our case, for example, the Java class is called “User” and the database table is instead called “Users”, in the plural, so we must explicitly specify the name of the latter through the “name”” attribute of the annotation as follows:

      @Entity
      @Table( name = "USERS")
      public class User {
      
  • @Column
    • It is used to indicate on which table column it is mapped the property of the annotated Java class. JPA by default assumes that the name of the class member is the same as the name of the table column on which it is mapped. If so, the @Column annotation may be omitted, otherwise it must be inserted and its “name” attribute must be valued with the exact name of the table column.
      Furthermore, the @Column annotation can be used to refine as much as possible the definition of the column on which the class property is mapped to, using other attributes such as “length“, “nullable“,” unique“, etc ..
  • @Id
    • Viene utilizzata per dichiarare una proprietà della classe java come primary key della tabella su cui è mappata la classe entity.
    • It is used to declare a property of the Java class as primary key of the table on which it is mapped to
  • @GeneratedValue
    • It is used to specify how to handle the objects identifiers and then the records of the table. It allows to use different criteria for handling ids through the value of the “strategy” attribute.

Let’s then modify our User class as follows:

package com.dede.app1st.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table( name = "USERS")
public class User {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name="user_id", nullable=false, unique=true)
	private int id;
	
	@Column(name="firstname", length=40, nullable=false)
	private String firstname;
	
	@Column(name="lastname", length=40, nullable=false)
	private String lastname;
	
	@Column(name="country", length=40, nullable=true)
	private String country;

        // GETTERS and SETTERS omitted for brevity
}

The picture below shows the correspondence between annotated properties of our User class and columns of the Users table that we created earlier in the PostgreSQL database.

JPA Entity class e tabella database

HIBERNATE CONFIGURATION
At this point we have to create the Hibernate configuration file with the information or, more precisely, the properties needed to connect to the PostgreSQL database.
SO, we create under “src” folder the file hibernate.cfg.xml where we have to specify what will be the driver that the DriverManager will use to connect to PostgreSQL, the address where the database is located, its name and the credentials, username and password, for access to it.
The content of our Hibernate configuration file is the following:

<hibernate-configuration>
	<session-factory>

		<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
		<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>

		<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/firstapp</property>
		<property name="hibernate.connection.username">postgres</property>
		<property name="hibernate.connection.password">dede</property>
		<property name="show_sql">false</property>

	</session-factory>
</hibernate-configuration>

Moreover, in the hibernate.cfg.xml file, we will have to map all of the classes that we want to manage using Hibernate. To do this we must specify the names of these classes in the “mapping” tag, as follows:

<mapping class="com.dede.app1st.model.User"/>

After making the Hibernate configuration, we must get the PostgreSQL jdbc driver and insert it within libraries used by the application.
The driver can be downloaded from http://jdbc.postgresql.org/download.html and once done we copy the “postgresql-9.3-1102.jdbc41.jar” file in the “WEB-INF/lib” folder.

The following picture shows the Eclipse project updated with the hibernate.cfg.xml file and its content and with the PostgreSQL jdbc driver library.
Hibernate configuration e postgres driver

EXECUTE A TRANSACTION
Now that we have prepared everything for users storage, creating a relational database and implementing an ORM layer with Hibernate, we must change the way in which our servlet handles these creation requests. Once the “create” button of the form for creating a new user servlet is pressed, which was formerly in charge of simply forward the request to a JSP page for displaying the message of successful creation and information of the user just created, it will now take care of actually store the user in the database, using the new available architecture.
To do this we use the following objects that Hibernate provides us:

  • Configuration
  • ServiceRegistry, StandardServiceRegistry and StandardServiceRegistryBuilder
  • SessionFactory
  • Session

“Configuration” is the class used to load the configuration. If, as in our case, the configuration is defined as default in the hibernate.cfg.xml file, it’s enough to instantiate a new object of this class and invoke on it the configure() method.

Configuration config = new Configuration().configure();

ServiceRegistry and StandardServiceRegistry are two interfaces and StandardServiceRegistryBuilder is the builder to use for the creation of objects that implement these interfaces, necessary for creating a SessionFactory. In Hibernate 4 is indeed necessary to pass an implementation of ServiceRegistry as parameter of the buildSessionFactory() method of the Configuration class.

ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();

SessionFactory, rather intuitively, is the factory that allows us to get the sessions through which we will perform operations on the database.

SessionFactory factory = config.buildSessionFactory(servReg);

Once obtained a session through the factory we can execute the transaction that allows us to insert into the database the record for the user we have created. The steps required to do this are:

  • Begin a transaction using the beginTransaction() method of the Session
  • Create the User object to store
  • Invoke the save() method of the Session, passing it the object to persist in the database
  • Commit the operation just performed, using the commit() method of the transaction
  • Close the session
Session session = factory.openSession();
session.beginTransaction();
User u = new User(request.getParameter("firstname"), request.getParameter("lastname"), request.getParameter("country"));
session.save(u);
session.getTransaction().commit();
session.close();

MODIFY THE REQUEST HANDLER
Using objects introduced and described in the previous paragraph we modify the doPost() method of our servlet AddUser so that it handles requests inserting a record in the database table.
The following picture shows the new implementation:

Hibernate transaction in servlet doPost()

RUN THE APPLICATION
At this point we run the application again, click on the link to create a new user, insert the information into the form and press “create.”

Running the web application in Tomcat

The information inserted in the input form are again sent using the POST method of the HTTP protocol to our Servlet AddUser that creates a new user, this time actually inserting it into the database. Then it shows us, as in the first version, information of the new user through the JSP page “useradd.jsp”.
In the following picture we see the result of this execution flow for creating the user:

Web Application - JSP user creation

At this point we have to verify if the new user has actually been inserted in our database. To do this we open pgAdmin3, the PostgreSQL administration console, and we make a select query on the “user” table of our database.

In pgAdmin click on the icon that opens the window in which we can run SQL statements. Then insert the query:

SELECT * FROM USERS

and as we can see we find the record related to the user we added through our application.

Web Application - Insert the record into the database

The tutorial continues with the next article: How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #4

This entry was posted in $1$s. Bookmark the permalink.

One thought on “How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #3

  1. Pingback: How to create a web application from scratch with Java, Eclipse, Tomcat, Hibernate and PostgreSQL – Part #4 | Dede Blog

Leave a Reply

Your email address will not be published. Required fields are marked *