Chuyển tới nội dung
Home » Hibernate Web Application Example | Create Application Class

Hibernate Web Application Example | Create Application Class

JSP Servlet Hibernate Database Web Application (Registration Module) | Java Guides

22.3 Example of managing book table through web application

Let’s take an example of managing book table through web application. Web application will have a feature of add a new book and display available books.

22.3.1 Design-

a) Design Book Entity

package com.tutorial.hibernate.entity; public class Book { private int id; private String isbn; private String name; private String author; private String publisher; private int price; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }

b. Create Book Table- Use the below create script to create book table.

CREATE TABLE ‘book’ ( ‘id’ int(11) NOT NULL AUTO_INCREMENT, ‘isbn’ varchar(255) DEFAULT NULL, ‘name’ varchar(255) DEFAULT NULL, ‘author’ varchar(255) DEFAULT NULL, ‘publisher’ varchar(255) DEFAULT NULL, ‘price’ int(11) DEFAULT NULL, PRIMARY KEY (‘id’); )

c. Hibernate.cfg.xml – Create a hibernate.cfg.xml file under src directory of web application.



jdbc:mysql://localhost:3306/tutorial root password org.hibernate.dialect.MySQLDialect true com.mysql.jdbc.Driver

d. book-mapping.hbm.xml – Create a book-mapping.hbm.xml file under src directory of web application.




This class contains the employee detail.

e. Create Servlets – We will create two servlets – one to insert the book data and another to retrieve all available book’s data.

GetDataServlet

package com.tutorial.hibernate.servlets; import java.io.IOException; import java.util.List; 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 org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import com.tutorial.hibernate.entity.Book; import com.tutorial.hibernate.util.HibernateUtils; @WebServlet(“/GetDataServlet”) public class GetDataServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SessionFactory factory = HibernateUtils.getSessionFactory(); Session session = factory.openSession(); Query query = session.createQuery(“from Book”); List

books = query.list(); session.flush(); session.close(); request.setAttribute(“books”, books); request.getRequestDispatcher(“booksDetails.jsp”).forward(request, response); } }

InsertBookServlet

package com.tutorial.hibernate.servlets; import java.io.IOException; 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 org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.tutorial.hibernate.entity.Book; import com.tutorial.hibernate.util.HibernateUtils; @WebServlet(“/InsertBookServlet”) public class InsertBookServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String isbn = request.getParameter(“isbn”); String name = request.getParameter(“name”); String author = request.getParameter(“author”); String publisher = request.getParameter(“publisher”); String price = request.getParameter(“price”); Book book = new Book(); book.setAuthor(author); book.setIsbn(isbn); book.setName(name); book.setPrice(Integer.parseInt(price)); book.setPublisher(publisher); SessionFactory factory = HibernateUtils.getSessionFactory(); Session session = factory.openSession(); Transaction tx = session.beginTransaction(); session.save(book); session.flush(); tx.commit(); session.close(); response.sendRedirect(“GetDataServlet”); } }

f. Create JSP files – We will create three JSP files, home page (index.jsp) , insert books screen(insertBook.jsp) and display books details (bookDetails.jsp).

index.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>

<br /> Manage Books<br />

Manage Books


Get Books


Insert Book


insertBook.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>

<br /> Manage Books<br />


<%@ page import=”java.util.List,com.tutorial.hibernate.entity.*” %>

Insert Book

Enter Books Details
ISBN
NAME
AUTHOR
PUBLISHER
PRICE


bookDetails.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>

<br /> Manage Books<br />


<%@ page import=”java.util.List,com.tutorial.hibernate.entity.*” %>

Available Books Details

<% List

books = (List

)request.getAttribute(“books”); %>

Total Number of Books are <%= books.size() %>

<% for(int i=0;i

<% } %>

ID ISBN NAME AUTHOR PUBLISHER PRICE
<%= book.getId() %> <%= book.getIsbn() %> <%= book.getName() %> <%= book.getAuthor() %> <%= book.getPublisher() %> <%= book.getPrice() %>




g. Deploy and Run the web application by accessing http://localhost:8080/ManageDatabase

Below will be home page (index,jsp)

Click on InsertBook link and it will display insertBooks.jsp

Add books details and click save

This will save the book details in database and will display the book table data. We can click on Get Books link (available on home screen) also to see the books.

You can verify that data is stored in table. Refer below table state

Modifying the Hibernate Configuration File

When you create a new project that uses the Hibernate framework, the IDE automatically creates the

hibernate.cfg.xml

configuration file at the root of the context classpath of the application (in the Files window,

src/java

). The file is located in the under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise you will edit the default properties specified in

hibernate.cfg.xml

to enable debug logging for SQL statements and to enable Hibernate’s session context management.

  1. Open


    hibernate.cfg.xml

    in the Design tab. You can open the file by expanding thenode under Source Packages in the Projects window and double-clicking

    hibernate.cfg.xml

    .

  2. In the multi-view XML editor, expand the Configuration Properties node under Optional Properties.

  3. Click Add to open the Add Hibernate Property dialog box.

  4. In the dialog box, select the


    hibernate.show_sql

    property and set the value to

    true

    . This enables the debug logging of the SQL statements.

  1. Expand the Miscellaneous Properties node and click Add.

  2. In the dialog box, select the


    properties hibernate.current_session_context_class

    and set the value to

    thread

    to enable Hibernate’s automatic session context management.

  1. Click Add again under the Miscellaneous Properties node and select


    hibernate.query.factory_class

    in the Property Name dropdown list.

  2. Select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value. Click OK.

If you click the XML tab in the editor you can see the file in XML view. Your file should look similar to the following (the three new properties are bold):



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### * true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory *


  1. Save your changes to the file.

You can close the file because you do not need to edit the file again.

JSP Servlet Hibernate Database Web Application (Registration Module) | Java Guides
JSP Servlet Hibernate Database Web Application (Registration Module) | Java Guides

List of Users

ID Name Email Country Actions


Edit


Delete



The taglib directive includes the JSTL (JavaServer Pages Standard Tag Library) core library, allowing the use of common tags like looping and output.

The

tag iterates over a collection of users and populates the table rows with the user details.

Create a User Form JSP Page – user-form.jsp

Next, we create a JSP page for creating a new User called user-form.jsp. Here’s its full source code:

<%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>

<br /> User Management Application<br />


User Management

Creating the JSF Managed Bean

In this exercise you will create a JSF managed bean. The methods in the managed bean are used for displaying data in the JSF pages and for accessing methods in the helper class to retrieve records. The JSF 2.0 specification enables you to use annotations in a bean class to identify the class as a JSF managed bean, to specify the scope and to specify a name for the bean.

To create the managed bean, perform the following steps.

  1. Right-click the


    dvdrental

    source package node and choose New > Other.

  2. Select JSF Managed Bean from the JavaServer Faces category. Click Next.

  3. Type FilmController for the Class Name.

You will use the Managed Bean name

filmController

as the value for the

inputText

and

commandButton

in the JSF page

index.xhtml

when calling methods in the bean.

  1. Select dvdrental for the Package.

  2. Type filmController for the Name that will be used for the managed bean.

  3. Set Scope to Session. Click Finish.

When you click Finish, the IDE creates the bean class and opens the class in the editor. The IDE added the

@ManagedBean

and

@SessionScoped

annotations.


@ManagedBean @SessionScoped public class FilmController { /** Creates a new instance of FilmController */ public FilmController() { } }

Note. Note that the name of the managed bean is not explicitly specified. By default, the name of the bean is the same as the class name and begins with a lower-case letter. If you want the name of the bean to be different from the class name, you can explicitly specify the name as a parameter of the

@ManagedBean

annotations (for example,

@ManagedBean(name="myBeanName")

.

  1. Add the following fields (in bold) to the class.


@ManagedBean @SessionScoped public class FilmController { *int startId; int endId; DataModel filmTitles; FilmHelper helper; private int recordCount = 1000; private int pageSize = 10; private Film current; private int selectedItemIndex;* }

  1. Add the following code (in bold) to create the FilmController instance and retrieve the films.


/** Creates a new instance of FilmController */ public FilmController() { *helper = new FilmHelper(); startId = 1; endId = 10; } public FilmController(int startId, int endId) { helper = new FilmHelper(); this.startId = startId; this.endId = endId; } public Film getSelected() { if (current == null) { current = new Film(); selectedItemIndex = -1; } return current; } public DataModel getFilmTitles() { if (filmTitles == null) { filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId)); } return filmTitles; } void recreateModel() { filmTitles = null; }*

  1. Add the following methods that are used to display the table and navigate the pages.* public boolean isHasNextPage() { if (endId + pageSize ⇐ recordCount) { return true; } return false; }

    public boolean isHasPreviousPage() { if (startId-pageSize > 0) { return true; } return false; }

    public String next() { startId = endId+1; endId = endId + pageSize; recreateModel(); return “index”; }

    public String previous() { startId = startId – pageSize; endId = endId – pageSize; recreateModel(); return “index”; }

    public int getPageSize() { return pageSize; }

    public String prepareView(){ current = (Film) getFilmTitles().getRowData(); return “browse”; } public String prepareList(){ recreateModel(); return “index”; } *

The methods that return “index” or “browse” will prompt the JSF navigation handler to try to open a page named

index.xhtml

or

browse.xhtml

. The JSF 2.0 specification enables the use of implicit navigation rules in applications that use Facelets technology. In this application, no navigation rules are configured in

faces-config.xml

. Instead, the navigation handler will try to locate a suitable page in the application.

  1. Add the following methods that access the helper class to retrieve additional film details.* public String getLanguage() { int langID = current.getLanguageByLanguageId().getLanguageId().intValue(); String language = helper.getLangByID(langID); return language; }

    public String getActors() { List actors = helper.getActorsByID(current.getFilmId()); StringBuffer totalCast = new StringBuffer(); for (int i = 0; i < actors.size(); i++) { Actor actor = (Actor) actors.get(i); totalCast.append(actor.getFirstName()); totalCast.append(” “); totalCast.append(actor.getLastName()); totalCast.append(” “); } return totalCast.toString(); }

    public String getCategory() { Category category = helper.getCategoryByID(current.getFilmId()); return category.getName(); }*

  1. Fix your imports (Ctrl-Shift-I) and save your changes.

You can use the code completion in the editor to help you type your code.

#14. JSP Servlet Hibernate CRUD Example
#14. JSP Servlet Hibernate CRUD Example

Creating the Database

This tutorial uses a MySQL database called

sakila

, a free sample MySQL database that is available from the MySQL site. The sakila database is not included when you install the IDE so you need to first create the database to follow this tutorial.

To create the sakila database you can download and install the Sakila Sample Database plugin using the Plugins manager. After you install the plugin the sakila database is added to the list of databases in the Create MySQL database dialog box.

For more information on configuring the IDE to work with MySQL, see the Connecting to a MySQL Database tutorial.

  1. Open the Plugins manager and install the Sakila Sample Database plugin.

  2. After installing the plugin, start the MySQL database by expanding the Databases node in the Services window, right-clicking the MySQL Server node and choosing Start.

  3. Right-click the MySQL Server node and choose Create Database.

  4. Select the Sakila database from the New Database Name drop down list in the Create MySQL Database dialog box. Click OK.

When you click OK a Sakila node appears under the MySQL Server node.

  1. Right-click the Sakila node and choose Connect.

When you click Connect a database connection node for the Sakila database (

jdbc:mysql://localhost:3306/sakila [username on Default]

) is listed under the Databases node. When a connection is open you can view the data in the database by expanding the connection node.

Creating the HibernateUtil.java Helper File

To use Hibernate you need to create a helper class that handles startup and that accesses Hibernate’s

SessionFactory

to obtain a Session object. The class calls

configure()

and loads the

hibernate.cfg.xml

configuration file and then builds the

SessionFactory

to obtain the Session object.

In this section you use the New File wizard to create the helper class

HibernateUtil.java

.

  1. Right-click the Source Packages node and select New > Other to open the New File wizard.

  2. Select Hibernate from the Categories list and HibernateUtil.java from the File Types list. Click Next.

  3. Type HibernateUtil for the class name and dvdrental for the package. Click Finish.

When you click Finish,

HibernateUtil.java

opens in the editor. You can close the file because you do not need to edit the file.

Hibernate  CRUD Project Step by Step
Hibernate CRUD Project Step by Step

Create Mapping Configuration File

This step is to create a mapping file that instructs Hibernate how to map the defined class or classes to the database tables.




This class contains the employee detail.

You should save the mapping document in a file with the format

.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. Let us see little detail about the mapping document −

  • The mapping document is an XML document having

    as the root element which contains all the

    elements.

  • The

    elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.

  • The element is optional element and can be used to create the class description.

  • The

    element maps the unique ID attribute in class to the primary key of the database table. The name attribute of the id element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

  • The

    element within the id element is used to generate the primary key values automatically. The class attribute of the generator element is set to native to let hibernate pick up either identity, sequence or hilo algorithm to create primary key depending upon the capabilities of the underlying database.

  • The element is used to map a Java class property to a column in the database table. The name attribute of the element refers to the property in the class and the column attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type.

There are other attributes and elements available, which will be used in a mapping document and I would try to cover as many as possible while discussing other Hibernate related topics.

Creating the FilmHelper.java Helper Class

You will now create a helper class in the

dvdrental

package that will be used to perform Hibernate queries on the database. You will use the Hibernate Query Language (HQL) editor to construct and test the queries for retrieving data. After you test the queries you will create methods in the helper class that construct and run the queries. You will then invoke the methods in the helper class from a JSF managed bean.

Creating the Class

In this section you use the New File wizard to create the helper class

FilmHelper.java

in the

dvdrental

package. You will create a Hibernate session by calling

getSessionFactory

in

HibernateUtil.java

and create some helper methods to create queries to retrieve data from the database. You will invoke the helper methods from the JSP pages.

  1. Right-click the


    dvdrental

    source package node and select New > Java Class to open the New File wizard.

  2. Type FilmHelper for the class name.

  3. Confirm that dvdrental is selected as the Package. Click Finish.

  4. Adding the following code (in bold) to create a Hibernate session.


public class FilmHelper { *Session session = null; public FilmHelper() { this.session = HibernateUtil.getSessionFactory().getCurrentSession(); }* }

  1. Right-click in the editor and choose Fix Imports (Alt-Shift-I; ⌘-Shift-I on Mac) to add any required import statements (


    org.hibernate.Session

    ) and save your changes.

You will now modify

FilmHelper.java

to add methods that query the DB.

Enumerating Film Titles and Retrieving Actors Using an HQL Query

In this exercise you will create a Hibernate Query Language (HQL) query that queries the database to retrieve a list of film titles from the Film table. You will then add a method that queries both the Actor and Film_actor tables to fetch the actors involved in a particular film.

The Film table has 1000 records so the method to retrieve the list of films should be able to retrieve records based on the

filmId

primary key. You will use the HQL editor to construct and test the HQL query. After you have created the correct query you will add a method to the class that can generate the proper query.

  1. Right-click the project node in the Projects window and choose Clean and Build.

  2. Right-click


    hibernate.cfg.xml

    in the Projects window and choose Run HQL Query to open the HQL query editor.

  3. Select hibernate.cfg from the drop down list in the toolbar.

  4. Test the connection by typing the following in the editor and clicking the Run HQL Query button ( images:./run_hql_query_16.png[title=”Run HQL Query button”] ) in the toolbar.


from Film

When you click Run HQL Query you can see the results of the query in the bottom window of the HQL query editor.

If you click the SQL button you can see the equivalent SQL query.


select film0_.film_id as col_0_0_ from sakila.film film0_

  1. Type the following query to retrieve the records in the Film table where the film id is between 100 and 200.


from Film as film where film.filmId between 100 and 200

The result window displays a list of records. Now that you have tested that the query returns the desired results, you can use the query in the helper class.

  1. Add the following method


    getFilmTitles

    to

    FilmHelper.java

    to retrieve the films where the film id is between a certain range specified by the variables

    startID

    and

    endID

    .


public List getFilmTitles(int startID, int endID) { List

filmList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Film as film where film.filmId between '"+startID+"' and '"+endID+"'"); filmList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return filmList; }


  1. Add the following method


    getActorsByID

    that retrieves the actors in a particular film. The method constructs the query using

    filmId

    as the input variable.


public List getActorsByID(int filmId){ List

actorList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Actor as actor where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='" + filmId + "')"); actorList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return actorList; }


  1. Fix your imports and save your changes.

When you fix your imports you want to choose

java.util.List

and

org.hibernate.Query

.

Adding Additional Helper Methods

You will now add additional helper methods that create queries based on an input variable. You can check the queries in the HQL query editor.

  1. Add the following method to retrieve a list of categories according to


    filmId

    .


public Category getCategoryByID(int filmId){ List

categoryList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='" + filmId + "')"); categoryList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return categoryList.get(0); }


  1. Add the following method to retrieve a single film according to


    filmId

    .


public Film getFilmByID(int filmId){ Film film = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Film as film where film.filmId=" + filmId); film = (Film) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return film; }

  1. Add the following method to retrieve the film language according to


    langId

    .


public String getLangByID(int langId){ Language language = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Language as lang where lang.languageId=" + langId); language = (Language) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return language.getName(); }

  1. Save your changes.

#15 Registration Page Using Hibernate ,Servlet , JSP | Hibernate Tutorials
#15 Registration Page Using Hibernate ,Servlet , JSP | Hibernate Tutorials

<%=exception.getMessage() %>



Deploying and Testing the Application

It’s time to see a demo of the above User Management web application. Deploy this web application to the Tomcat server.

Type the following URL in your web browser to access the User Management application: http://localhost:8080/jsp-servlet-jdbc-mysql-crud-example/

Create a new User

Edit a User

List of all Users

GitHub Repository – Download Source Code

The source code for this tutorial (User Management) is available on my GitHub repository.

Building Web Applications with Hibernate

In this topic, we use the NetBeans IDE to create and deploy a web application that displays data from a database. The web application uses the Hibernate framework as the persistence layer for retrieving and storing plain old Java objects (POJOs) to a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The present topic demonstrates how to add support for the Hibernate framework to the IDE and create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, we add a JSF managed bean and JSF 2.0 pages to display the data.

Softwares Used

To complete this topic, we will need the following software resources :—

  • NetBeans IDE 8.2
  • Java Development Kit (JDK) 8
  • GlassFish server 4.1.1
  • MySQL 5.0 with Type 4 driver
  • Sakila MySQL Sample Database Plugin

Developing Hibernate Application

We follow these steps one-by-one to create web application based on Hibernate.

Step 1: Creating the Database

This tutorial uses a MySQL database called sakila, a free sample MySQL database that is available from the MySQL site. The sakila database is not included when we install the IDE so we need to first create the database to follow this tutorial.

To create the sakila database we can download and install the Sakila Sample Database plugin using the Plugins manager. After we install the plugin the sakila database is added to the list of databases in the Create MySQL database dialog box. To get information on configuring the NetBeans IDE to work with MySQL, have a look at the Connecting to a MySQL Database tutorial.

  1. Open the Plugins manager and install the Sakila Sample Database plugin.
  2. After installing the plugin, start the MySQL database by expanding the Databases node in the Services window, right-clicking the MySQL Server node and choosing Start.
  3. Right-click the MySQL Server node and choose Create Database.
  4. Select the Sakila database from the New Database Name drop down list in the Create MySQL Database dialog box. Click OK.

    When we click OK a Sakila node appears under the MySQL Server node.

  5. Right-click the Sakila node and choose Connect.

When we click Connect a database connection node for the Sakila database (jdbc:mysql://localhost:3306/sakila [root on Default schema]) is listed under the Databases node. When a connection is open we can view the data in the database by expanding the connection node.

Step 2: Creating the Web Application Project

In this exercise we will create a web application project and add the Hibernate libraries to the project. When we create the project, we will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

  1. Choose File > New Project (Ctrl-Shift-N) from the main menu. Select Web Application from the Java Web category and click Next.
  2. Type DVDStore for the project name and set the project location.
  3. Deselect the Use Dedicated Folder option, if selected. Click Next.

    For this tutorial there is little reason to copy project libraries to a dedicated folder because we will not need to share libraries with other users.

  4. Set the server to the GlassFish Server and set the Java EE Version to Java EE 6 Web. Click Next.
  5. Select the JavaServer Faces checkbox and use the default JSF 2.2 libraries.
  6. Select the Hibernate 4.3.1 checkbox in the list of frameworks.
  7. Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, we need to create the database connection.

When we click Finish, the IDE creates the web application project and opens the hibernate.cfg.xml file and index.xhtml in the editor.

If we expand the Libraries node in the Projects window, we can see that the IDE added the Hibernate libraries to the to the project.

Step 3: Modifying the Hibernate Configuration File

When we create a new project that uses the Hibernate framework, the IDE automatically creates the hibernate.cfg.xml configuration file at the root of the context classpath of the application (in the Files window, src/java). The file is located in the under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. We can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise we will edit the default properties specified in hibernate.cfg.xml to enable debug logging for SQL statements and to enable Hibernate’s session context management.

  1. Open hibernate.cfg.xml in the Design tab. We can open the file by expanding the node under Source Packages in the Projects window and double-clicking hibernate.cfg.xml.
  2. In the multi-view XML editor, expand the Configuration Properties node under Optional Properties.
  3. Click Add to open the Add Hibernate Property dialog box.
  4. In the dialog box, select the property named hibernate.show_sql and set the value to true. This enables the debug logging of the SQL statements.
  5. Expand the Miscellaneous Properties node and click Add.
  6. In the dialog box, select the property hibernate.current_session_context_class and set the value to thread to enable Hibernate’s automatic session context management.

7. Click Add again under the Miscellaneous Properties node and select hibernate.query.factory_class in the Property Name dropdown list.

8. Select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value. Click OK.

If we click the XML tab in the editor we can see the file in XML view. Our file should look similar to the following (the 3 new properties are bold):


org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root system true thread org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

9. Save the changes to the file.

We can close the file because we do not need to edit the file again.

Step 4: Creating the HibernateUtil.java Helper File

To use Hibernate we need to create a helper class that handles startup and that accesses Hibernate’s SessionFactory to obtain a Session object. The class calls configure() and loads the hibernate.cfg.xml configuration file and then builds the SessionFactory to obtain the Session object.

In this section we use the New File wizard to create the helper class HibernateUtil.java.

  1. Right-click the Source Packages node and select New > Other to open the New File wizard.
  2. Select Hibernate from the Categories list and HibernateUtil.java from the File Types list. Click Next.
  3. Type HibernateUtil for the class name and dvdrental for the package. Click Finish.

When we click Finish, HibernateUtil.java opens in the editor. We can close the file because we don’t need to edit the file.

Step 5: Generating Hibernate Mapping Files and Java Classes

In this tutorial we use a POJO (plain old Java object) to represent the data in each of the tables in the database that we will use. The Java class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map the POJOs to the tables we can use a Hibernate mapping file or use annotations in the class.

We can use the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables. When using the wizard we select all the tables for which we want POJOs and mapping files and the IDE then generates the files for us based on the database tables and adds the mapping entries to hibernate.cfg.xml. When we use the wizard we can choose the files that we want the IDE to generate (only the POJOs, for example) and select code generation options (generate code that uses EJB 3 annotations, for example).

5.Creating the Hibernate Reverse Engineering File

If we want to use the Hibernate Mapping Files and POJOs from a Database wizard, we first need to create a hibernate.reveng.xml reverse engineering file. The Hibernate Mapping Files and POJOs from a Database wizard requires hibernate.reveng.xml and hibernate.cfg.xml.

The reverse engineering file enables us to have greater control over the database mapping strategy. The Hibernate Reverse Engineering Wizard creates a reverse engineering file with a default configuration that we can edit in the XML editor.

To create the Hibernate reverse engineering file, perform the following steps.

    1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.
    2. Select Hibernate Reverse Engineering Wizard in the Hibernate category. Click Next.
    3. Specify hibernate.reveng as the File Name and src/java for the Folder. Click Next.
    4. Select hibernate.cfg.xml from the Configuration File drop down list, if not selected.
    5. Select the following tables from Available Tables and click Add to add the tables to Selected Tables.

      • actor
      • category
      • film
      • film_actor
      • film_category
      • language

Click Finish.

The wizard generates a hibernate.reveng.xml reverse engineering file and opens the file in the editor. We can close the reverse engineering file because we don’t need to edit the file.

5.Creating the Hibernate Mapping Files and POJOs

We can use the Hibernate Mapping Files and POJOs from a Database wizard to generate files for we. The wizard can generate a POJO and a corresponding mapping file for each table that we select in the wizard. The mapping files are XML files that contain data about how the columns in the tables are mapped to the fields in the POJOs. We need to have the hibernate.reveng.xml and hibernate.cfg.xml files to use the wizard.

To create the POJOS and mapping files using a wizard, perform the following steps.

    1. Right-click Source Packages node in the Projects window and choose New > Other to open the New File wizard.
    2. Select Hibernate Mapping Files and POJOs from a Database in the Hibernate category. Click Next.
    3. Ensure that the hibernate.cfg.xml and hibernate.reveng.xml files are selected in the drop down lists.
    4. Select JDK 5 Language Features under the “General Settings” options. Don’t choose the EJB 3 annotations here.
    5. Ensure that the Domain Code and Hibernate XML Mappings options under the “Code Generation Settings” are selected.
    6. Select dvdrental for the Package name. Click Finish.

When we click Finish the IDE generates POJOs and Hibernate mapping files with the fields mapped to the columns specified in hibernate.reveng.xml. The IDE also adds mapping entries to this file (shown in bold font).


org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root system true thread org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

Note. Confirm that the mapping elements are listed after the property elements in the hibernate.cfg.xml file.

We can expand the dvdrental package to see the files generated by the wizard.

Step 6: Creating the FilmHelper.java Helper Class

We will now create a helper class in the dvdrental package that will be used to perform Hibernate queries on the database. We will use the Hibernate Query Language (HQL) editor to construct and test the queries for retrieving data. After we test the queries we will create methods in the helper class that construct and run the queries. We will then invoke the methods in the helper class from a JSF managed bean.

6.Creating the Helper Class

In this section we use the New File wizard to create the helper class FilmHelper.java in the dvdrental package. We will create a Hibernate session by calling getSessionFactory() in HibernateUtil.java and create some helper methods to create queries to retrieve data from the database. We will invoke the helper methods from the JSP pages.

    1. Right-click the dvdrental source package node and select New > Java Class to open the New File wizard.
    2. Type FilmHelper for the class name.
    3. Confirm that dvdrental is selected as the Package. Click Finish.
    4. Adding the following code (in bold) to create a Hibernate session.

      public class FilmHelper { Session session = null; public FilmHelper() { this.session = HibernateUtil.getSessionFactory().openSession(); } }

    5. Right-click in the editor and choose Fix Imports (Alt-Shift-I) to add any required import statements (org.hibernate.Session) and save the changes.

We will now modify FilmHelper.java to add methods that query the DB.

6.Enumerating Film Titles and Retrieving Actors Using an HQL Query

In this exercise, we will create a Hibernate Query Language (HQL) query that queries the database to retrieve a list of film titles from the Film table. We will then add a method that queries both the Actor and Film_actor tables to fetch the actors involved in a particular film.

The Film table has 1000 records so the method to retrieve the list of films should be able to retrieve records based on the filmId primary key. We will use the HQL editor to construct and test the HQL query. After we have created the correct query we will add a method to the class that can generate the proper query.

    1. Right-click the project node in the Projects window and choose Clean and Build.
    2. Right-click hibernate.cfg.xml in the Projects window and choose Run HQL Query to open the HQL query editor.
    3. Select hibernate.cfg from the drop down list in the toolbar.
    4. Test the connection by typing the following in the editor and clicking the Run HQL Query button ( ) in the toolbar.

      from Film

      When we click Run HQL Query we can see the results of the query in the bottom window of the HQL query editor.

      If we click the SQL button we can see the equivalent SQL query.

      select film0_.film_id as col_0_0_ from sakila.film film0_

    5. We now type the following query to retrieve the records in the Film table where the film id is between 100 and 200.

      from Film as film where film.filmId between 100 and 200

      The result window displays a list of records. Now that we have tested that the query returns the desired results, we can use the query in the helper class.

    6. Add the following method getFilmTitles() to FilmHelper.java to retrieve the films where the film id is between a certain range specified by the variables startID and endID.

      public List getFilmTitles(int startID, int endID) { List filmList = null; try { org.hibernate.Transaction tx = session.getTransaction();

      Query q = session.createQuery(“from Film as film where film.filmId between ‘” + startID + “‘ and ‘” + endID + “‘”);filmList = (List) q.list();session.getTransaction().commit(); }catch (Exception e) { e.printStackTrace(); } return filmList; }

    7. Add the following method getActorsByID() that retrieves the actors in a particular film. The method constructs the query using filmId as the input variable.

      public List getActorsByID(int filmId){ List actorList = null; try {

      org.hibernate.Transaction tx = session.getTransaction();Query q = session.createQuery(“from Actor as actor where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='” + filmId + “‘)”);actorList = (List) q.list();session.getTransaction().commit();}catch (Exception e) {e.printStackTrace();} return actorList; }

    8. Fix the imports and save necessary changes.

      When we fix the imports we want to choose java.util.List and org.hibernate.Query.

6.Adding Additional Helper Methods

We will now add additional helper methods to FilmHelper.java to create queries based on an input variable. We can check the queries in the HQL query editor.

    1. Add the following method to retrieve a list of categories according to filmId.

      public Category getCategoryByID(int filmId){ List categoryList = null; try { org.hibernate.Transaction tx = session.getTransaction();

      Query q = session.createQuery(“from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='” + filmId + “‘)”);categoryList = (List) q.list();session.getTransaction().commit(); }catch (Exception e) { e.printStackTrace(); } return categoryList.get(0); }

    2. We add the following method to retrieve a single film according to filmId.

      public Film getFilmByID(int filmId){ Film film = null; try { org.hibernate.Transaction tx = session.getTransaction();

      Query q = session.createQuery(“from Film as film where film.filmId=” + filmId);film = (Film) q.uniqueResult();session.getTransaction().commit(); }catch (Exception e) { e.printStackTrace(); } return film; }

    3. We add the following method to retrieve the film language according to langId.

      public String getLangByID(int langId){ Language language = null; try { org.hibernate.Transaction tx = session.getTransaction();

      Query q = session.createQuery(“from Language as lang where lang.languageId=” + langId);language = (Language) q.uniqueResult();session.getTransaction().commit(); }catch (Exception e) { e.printStackTrace(); } return language.getName(); }

    4. Save the changes.
  1. Add the following method to retrieve a list of categories according to filmId.
Step 7: Creating the JSF Managed Bean

In this step we will create a JSF managed bean. The methods in the managed bean are used for displaying data in the JSF pages and for accessing methods in the helper class to retrieve records. The JSF 2.0 specification enables us to use annotations in a bean class to identify the class as a JSF managed bean, to specify the scope and to specify a name for the bean.

To create the managed bean, perform the following steps.

  1. Right-click the dvdrental source package node and choose New > Other.
  2. Select JSF Managed Bean from the JavaServer Faces category. Click Next.
  3. Type FilmController for the Class Name.

    We will use the Managed Bean name filmController as the value for the inputText and commandButton in the JSF page index.xhtml when calling methods in the bean.

  4. Select dvdrental for the Package.
  5. Type filmController for the Name that will be used for the managed bean.
  6. Set Scope to Session. Click Finish.

When we click Finish, the IDE creates the bean class and opens the class in the editor. The IDE added the @Named and @SessionScoped annotations. We have also added the annotation @ManagedBean from javax.faces.bean.ManagedBean. See it below.

@Named(value = “filmController”)@ManagedBean@SessionScopedpublic class FilmController implements Serializable {/** Creates a new instance of FilmController */ public FilmController() { } }

After addting fields & methods and fixing the imports the final code would look like this:

package dvdrental;import javax.inject.Named;import javax.enterprise.context.SessionScoped;import java.io.Serializable;import java.util.List;import javax.faces.bean.ManagedBean;import javax.faces.model.DataModel;import javax.faces.model.ListDataModel;@Named(value = “filmController”)@ManagedBean@SessionScopedpublic class FilmController implements Serializable {int startId;int endId;DataModel filmTitles;FilmHelper helper;private int recordCount = 1000;private int pageSize = 10;private Film current;private int selectedItemIndex;/*** Creates a new instance of FilmController*/public FilmController() {helper = new FilmHelper();startId = 1;endId = 10;}public FilmController(int startId, int endId) {helper = new FilmHelper();this.startId = startId;this.endId = endId;}public Film getSelected() {if (current == null) {current = new Film();selectedItemIndex = -1;}return current;}public DataModel getFilmTitles() {if (filmTitles == null) {filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId));}return filmTitles;}void recreateModel() {filmTitles = null;}public boolean isHasNextPage() {if (endId + pageSize <= recordCount) {return true;}return false;}public boolean isHasPreviousPage() {if (startId – pageSize > 0) {return true;}return false;}public String next() {startId = endId + 1;endId = endId + pageSize;recreateModel();return “index”;}public String previous() {startId = startId – pageSize;endId = endId – pageSize;recreateModel();return “index”;}public int getPageSize() {return pageSize;}public String prepareView() {current = (Film) getFilmTitles().getRowData();return “browse”;}public String prepareList() {recreateModel();return “index”;}public String getLanguage() {int langID = current.getLanguageByLanguageId().getLanguageId().intValue();String language = helper.getLangByID(langID);return language;}public String getActors() {List actors = helper.getActorsByID(current.getFilmId());StringBuffer totalCast = new StringBuffer();for (int i = 0; i < actors.size(); i++) {Actor actor = (Actor) actors.get(i);totalCast.append(actor.getFirstName());totalCast.append(” “);totalCast.append(actor.getLastName());totalCast.append(” “);}return totalCast.toString();}public String getCategory() {Category category = helper.getCategoryByID(current.getFilmId());return category.getName();}}

Step 8: Creating the Web Pages

In this exercise we will create two web pages for displaying the data. We will modify the index.xhtml generated by the IDE to add a table that displays the films in the database. We will then create browse.xhtml to display a film’s details when we click the “View” link in the table. We will also create a JSF template page that is used by index.xhtml and browse.xhtml.

8.Creating template.xhtml

We will first create the JSF Facelets template template.xhtml that is used in the composition of the index.xhtml and browse.xhtml pages.

    1. Right-click the DVDStore project node in the Projects window and choose New > Other.
    2. Select Facelets Template in the JavaServer Faces category. Click Next.
    3. Type template for the File Name and choose the first CSS layout style.
    4. Click Finish.

      When we click Finish, the file template.xhtml opens in the editor. The template contains the following default code. The color marked code within and will be replaced a little bit later.

      <br /> Facelets Template<br />


      Top

      Content

      5. Modify the

      element to change the default generated name to “body”.


      Content

      6. Save the changes.

The content enclosed within the element in index.xhtml and browse.xhtml will be inserted into the location identified with Content in the template. The CSS files also have to be added within

and

.

The final code would look like this:


xmlns:ui=”http://java.sun.com/jsf/facelets”xmlns:h=”http://java.sun.com/jsf/html”>

<br /> Facelets Template<br />


Top

Content

8.2 Modifying index.xhtml

When we created the web application, the IDE automatically generated the page index.xhtml. In this exercise we modify the page to display a list of film titles. The JSF page calls the methods in the JSF Managed Bean FilmController to retrieve the list of films and then displays a table with the film titles and descriptions.

    1. Expand the Web Pages folder in the Projects window and open index.xhtml in the editor.

      The New Project wizard generated the following default index.xhtml page.



      <br /> Facelet Title<br />


      Hello from Facelets

    2. Modify the page to use the JSF

      and

      elements and add a

      element.

      When we start typing the tags, the IDE adds xmlns:ui=”http://java.sun.com/jsf/facelets” tag library declaration.

      The

      and

      elements are used in combination with the page template that we will create. The

      element references the location of the template that will be used by this page. The

      element references the position in the template that the enclosed code will occupy.





    3. Add the following navigation links that call the previous and next methods in the JSF managed bean.
    4. Add the following dataTable element (in bold) to generate the table to display the retrieved items.
    5. Save the changes.
  1. Expand the Web Pages folder in the Projects window and open index.xhtml in the editor.

The index page will now display a list of film titles in the database. Each row in the table includes a “View” link that invokes the prepareView method in the managed bean. The prepareView method returns “browse” and will open browse.xhtml.

Note. When we type the

tag, the IDE will add xmlns:f=”http://java.sun.com/jsf/core tag library declaration. Confirm that the tag library is declared in the file.xmlns:f=”http://java.sun.com/jsf/core tag library declaration.

8.3 Creating browse.xhtml

We will now create the browse.xhtml page for displaying details of the selected film. We can use the Facelets Template Client wizard to create the page based on the JSF Facelets template template.xhtml that we created.

    1. Right-click DVDStore project node in the Projects window and choose New > Other.
    2. Select Facelets Template Client in the JavaServer Faces category. Click Next.
    3. Type browse for the File Name.
    4. Locate the Template for the page by clicking Browse to open the Browse Files dialog box.
    5. Expand the Web Pages folder and select template.xhtml. Click Select File.
    6. Select

      for the Generated Root Tag. Click Finish.

      When we click Finish, the file browse.xhtml opens in the editor with the following code.



      top


      body

      We can see that the new file specifies the template.xhtml file and that the tag

      has the property name=”body”

    7. Add the following code (in bold) between the

      tags to create the form and call the methods in the managed bean FilmController to retrieve the data and populate the form.



      top

      We can see that browse.xhtml and index.xhtml will use the same page template.

    8. Save the changes.
Step 9: Running the Project

The basics of the application are now complete. We can now run the application to check if everything is working correctly.

1. Click Run Main Project in the main toolbar or right-click the DVDStore application node in the Projects window and choose Run.

The IDE saves all changed files, builds the application, and deploys the application to the server. The IDE opens a browser window to the URL http://localhost:8484/DVDStore/ that displays the list of films.

2. In our browser, click “View” for the first one in the list to load browse.xhtml to view the film details.

  • Hibernate Tutorial
  • Hibernate – Home
  • ORM – Overview
  • Hibernate – Overview
  • Hibernate – Architecture
  • Hibernate – Environment
  • Hibernate – Configuration
  • Hibernate – Sessions
  • Hibernate – Persistent Class
  • Hibernate – Mapping Files
  • Hibernate – Mapping Types
  • Hibernate – Examples
  • Hibernate – O/R Mappings
  • Hibernate – Annotations
  • Hibernate – Query Language
  • Hibernate – Criteria Queries
  • Hibernate – Native SQL
  • Hibernate – Caching
  • Hibernate – Batch Processing
  • Hibernate – Interceptors
  • Hibernate Useful Resources
  • Hibernate – Questions and Answers
  • Hibernate – Quick Guide
  • Hibernate – Useful Resources
  • Hibernate – Discussion

Hibernate – Examples

Let us now take an example to understand how we can use Hibernate to provide Java persistence in a standalone application. We will go through the different steps involved in creating a Java Application using Hibernate technology.

Creating the Web Pages

In this exercise you will create two web pages for displaying the data. You will modify the

index.xhtml

generated by the IDE to add a table that displays the films in the database. You will then create

browse.xhtml

to display a film’s details when you click the “View” link in the table. You will also create a JSF template page that is used by

index.xhtml

and

browse.xhtml

.

For more about using JSF 2.0 and Facelets templates, see Introduction to JavaServer Faces 2.0

Creating template.xhtml

You will first create the JSF Facelets template

template.xhtml

that is used in the composition of the

index.xhtml

and

browse.xhtml

pages.

  1. Right-click the DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template in the JavaServer Faces category. Click Next.

  3. Type template for the File Name and choose the first CSS layout style.

  4. Click Finish.

When you click Finish, the file

template.xhtml

opens in the editor. The template contains the following default code.



Top

Content


  1. Modify the

    element to change the default generated name to “body”.


Content

  1. Save your changes.

The content enclosed within the element in

index.xhtml

and

browse.xhtml

will be inserted into the location identified with


Content


in the template.

Modifying index.xhtml

When you created the web application, the IDE automatically generated the page

index.xhtml

. In this exercise you modify the page to display a list of film titles. The JSF page calls the methods in the JSF Managed Bean FilmController to retrieve the list of films and then displays a table with the film titles and descriptions.

  1. Expand the Web Pages folder in the Projects window and open


    index.xhtml

    in the editor.

The New Project wizard generated the following default

index.xhtml

page.




<br /> Facelet Title<br />


Hello from Facelets


  1. Modify the page to use the JSF

    andelements and add aelement.

When you start typing the tags, the IDE adds

xmlns:ui="http://java.sun.com/jsf/facelets"

tag library declaration.

The and elements are used in combination with the page template that you will create. The element references the location of the template that will be used by this page. The element references the position in the template that the enclosed code will occupy.

  1. Add the following navigation links that call the


    previous

    and

    next

    methods in the JSF managed bean.




* *


  1. Add the following


    dataTable

    element (in bold) to generate the table to display the retrieved items.



* *

  1. Save your changes.

The index page will now display a list of film titles in the database. Each row in the table includes a “View” link that invokes the

prepareView

method in the managed bean. The

prepareView

method returns “browse” and will open

browse.xhtml

.

Note. When you type the tag, the IDE will add

xmlns:f="http://java.sun.com/jsf/core

tag library declaration. Confirm that the tag library is declared in the file.

Creating browse.xhtml

You will now create the

browse.xhtml

page for displaying details of the selected film. You can use the Facelets Template Client wizard to create the page based on the JSF Facelets template

template.xhtml

that you created.

  1. Right-click DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template Client in the JavaServer Faces category. Click Next.

  1. Type browse for the File Name.

  2. Locate the Template for the page by clicking Browse to open the Browse Files dialog box.

  3. Expand the Web Pages folder and select


    template.xhtml

    . Click Select File.

  1. Select

    for the Generated Root Tag. Click Finish.

When you click Finish, the file

browse.xhtml

opens in the editor with the following code.




top


body


You can see that the new file specifies the

template.xhtml

file and that the tag has the property

name="body"

  1. Add the following code (in bold) between the

    tags to create the form and call the methods in the managed bean FilmController to retrieve the data and populate the form.




top


* *


You can see that

browse.xhtml

and

index.xhtml

will use the same page template.

  1. Save your changes.

#4. Hibernate CRUD Example in Eclipse IDE with Maven and MySQL Database
#4. Hibernate CRUD Example in Eclipse IDE with Maven and MySQL Database

Edit User Add New User

User Name: User Email: Country:


The above page acts for both functionalities to create a new User and Edit the same user.

Creating Error JSP page

Here’s the code of the Error.jsp page which simply shows the exception message:

<%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″ isErrorPage=”true” %>

<br /> Error<br />


Error

Create Database Tables

Second step would be creating tables in your database. There would be one table corresponding to each object, you are willing to provide persistence. Consider above objects need to be stored and retrieved into the following RDBMS table −

create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );

Hibernate or JPA: Which One is Right for You?
Hibernate or JPA: Which One is Right for You?

Creating the JSF Managed Bean

In this exercise you will create a JSF managed bean. The methods in the managed bean are used for displaying data in the JSF pages and for accessing methods in the helper class to retrieve records. The JSF 2.0 specification enables you to use annotations in a bean class to identify the class as a JSF managed bean, to specify the scope and to specify a name for the bean.

To create the managed bean, perform the following steps.

  1. Right-click the


    dvdrental

    source package node and choose New > Other.

  2. Select JSF Managed Bean from the JavaServer Faces category. Click Next.

  3. Type FilmController for the Class Name.

You will use the Managed Bean name

filmController

as the value for the

inputText

and

commandButton

in the JSF page

index.xhtml

when calling methods in the bean.

  1. Select dvdrental for the Package.

  2. Type filmController for the Name that will be used for the managed bean.

  3. Set Scope to Session. Click Finish.

When you click Finish, the IDE creates the bean class and opens the class in the editor. The IDE added the

@ManagedBean

and

@SessionScoped

annotations.


@ManagedBean @SessionScoped public class FilmController { /** Creates a new instance of FilmController */ public FilmController() { } }

Note. Note that the name of the managed bean is not explicitly specified. By default, the name of the bean is the same as the class name and begins with a lower-case letter. If you want the name of the bean to be different from the class name, you can explicitly specify the name as a parameter of the

@ManagedBean

annotations (for example,

@ManagedBean(name="myBeanName")

.

  1. Add the following fields (in bold) to the class.


@ManagedBean @SessionScoped public class FilmController { *int startId; int endId; DataModel filmTitles; FilmHelper helper; private int recordCount = 1000; private int pageSize = 10; private Film current; private int selectedItemIndex;* }

  1. Add the following code (in bold) to create the FilmController instance and retrieve the films.


/** Creates a new instance of FilmController */ public FilmController() { *helper = new FilmHelper(); startId = 1; endId = 10; } public FilmController(int startId, int endId) { helper = new FilmHelper(); this.startId = startId; this.endId = endId; } public Film getSelected() { if (current == null) { current = new Film(); selectedItemIndex = -1; } return current; } public DataModel getFilmTitles() { if (filmTitles == null) { filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId)); } return filmTitles; } void recreateModel() { filmTitles = null; }*

  1. Add the following methods that are used to display the table and navigate the pages.* public boolean isHasNextPage() { if (endId + pageSize ⇐ recordCount) { return true; } return false; }

    public boolean isHasPreviousPage() { if (startId-pageSize > 0) { return true; } return false; }

    public String next() { startId = endId+1; endId = endId + pageSize; recreateModel(); return “index”; }

    public String previous() { startId = startId – pageSize; endId = endId – pageSize; recreateModel(); return “index”; }

    public int getPageSize() { return pageSize; }

    public String prepareView(){ current = (Film) getFilmTitles().getRowData(); return “browse”; } public String prepareList(){ recreateModel(); return “index”; } *

The methods that return “index” or “browse” will prompt the JSF navigation handler to try to open a page named

index.xhtml

or

browse.xhtml

. The JSF 2.0 specification enables the use of implicit navigation rules in applications that use Facelets technology. In this application, no navigation rules are configured in

faces-config.xml

. Instead, the navigation handler will try to locate a suitable page in the application.

  1. Add the following methods that access the helper class to retrieve additional film details.* public String getLanguage() { int langID = current.getLanguageByLanguageId().getLanguageId().intValue(); String language = helper.getLangByID(langID); return language; }

    public String getActors() { List actors = helper.getActorsByID(current.getFilmId()); StringBuffer totalCast = new StringBuffer(); for (int i = 0; i < actors.size(); i++) { Actor actor = (Actor) actors.get(i); totalCast.append(actor.getFirstName()); totalCast.append(” “); totalCast.append(actor.getLastName()); totalCast.append(” “); } return totalCast.toString(); }

    public String getCategory() { Category category = helper.getCategoryByID(current.getFilmId()); return category.getName(); }*

  1. Fix your imports (Ctrl-Shift-I) and save your changes.

You can use the code completion in the editor to help you type your code.

22.4 Using JNDI and Data Source

Web applications are multi user application and managed by web or application servers. Instead of opening connection at each request, we can use datasource and instead of configuring the database details, we can use datasource.

To do so, add below lines in context.xml file of tomcat (Available under conf directory of tomcat installation directory)

Once Done, restart the server. Hibernate.cfg.xml file will just need to configure datasource. Refer below hibernate.cfg.xml file for JNDI



java:/comp/env/jdbc/HibernateTutorial org.hibernate.dialect.MySQLDialect true

Hibernate Example using XML in Eclipse

Here, we are going to create a simple example of hibernate application using eclipse IDE. For creating the first hibernate application in Eclipse IDE, we need to follow the following steps:

1) Create the java project

Create the java project by File Menu – New – project – java project . Now specify the project name e.g. firsthb then next – finish .

2) Add jar files for hibernate

To add the jar files Right click on your project – Build path – Add external archives. Now select all the jar files as shown in the image given below then click open.

Download the required jar file

In this example, we are connecting the application with oracle database. So you must add the ojdbc14.jar file.

download the ojdbc14.jar file

3) Create the Persistent class

Here, we are creating the same persistent class which we have created in the previous topic. To create the persistent class, Right click on src – New – Class – specify the class with package name (e.g. com.javatpoint.mypackage) – finish .

Employee.java
4) Create the mapping file for Persistent class

Here, we are creating the same mapping file as created in the previous topic. To create the mapping file, Right click on src – new – file – specify the file name (e.g. employee.hbm.xml) – ok. It must be outside the package.

employee.hbm.xml
5) Create the Configuration file

The configuration file contains all the informations for the database such as connection_url, driver_class, username, password etc. The hbm2ddl.auto property is used to create the table in the database automatically. We will have in-depth learning about Dialect class in next topics. To create the configuration file, right click on src – new – file. Now specify the configuration file name e.g. hibernate.cfg.xml.

hibernate.cfg.xml
6) Create the class that retrieves or stores the persistent object

In this class, we are simply storing the employee object to the database.

7) Run the application
Spring Boot Simple Project step by step using Mysql Database
Spring Boot Simple Project step by step using Mysql Database


<%@page contentType="text/html"%>


<%@page pageEncoding="UTF-8"%>


html


head


meta


http-equiv


"Content-Type"


content


"text/html; charset=UTF-8"


title


>Registration Form


title




head


style


body {


font-family: Verdana, Geneva, sans-serif;


font-size: 14px;


background: #006400;


.clearfix {


&:after {


content: "";


display: block;


clear: both;


visibility: hidden;


height: 0;


.form_wrapper {


background: #fff;


width: 600px;


max-width: 100%;


box-sizing: border-box;


padding: 25px;


margin: 8% auto 0;


position: relative;


z-index: 1;


border-top: 5px solid $yellow;


-webkit-box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);


-moz-box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);


box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);


-webkit-transform-origin: 50% 0%;


transform-origin: 50% 0%;


-webkit-transform: scale3d(1, 1, 1);


transform: scale3d(1, 1, 1);


-webkit-transition: none;


transition: none;


-webkit-animation: expand 0.8s 0.6s ease-out forwards;


animation: expand 0.8s 0.6s ease-out forwards;


opacity: 0;


h2 {


font-size: 1.5em;


line-height: 1.5em;


margin: 0;


.title_container {


text-align: center;


padding-bottom: 15px;


h3 {


font-size: 1.1em;


font-weight: normal;


line-height: 1.5em;


margin: 0;


label {


font-size: 12px;


.row {


margin: 10px -15px;


>div {


padding: 0 15px;


box-sizing: border-box;


.col_half {


width: 50%;


float: left;


.input_field {


position: relative;


margin-bottom: 20px;


-webkit-animation: bounce 0.6s ease-out;


animation: bounce 0.6s ease-out;


>span {


position: absolute;


left: 0;


top: 0;


color: #333;


height: 100%;


border-right: 1px solid $grey;


text-align: center;


width: 30px;


>i {


padding-top: 10px;


.textarea_field {


>span {


>i {


padding-top: 10px;


input {


&[type="text"], &[type="email"], &[type="password"] {


width: 100%;


padding: 8px 10px 9px 35px;


height: 35px;


border: 1px solid $grey;


box-sizing: border-box;


outline: none;


-webkit-transition: all 0.30s ease-in-out;


-moz-transition: all 0.30s ease-in-out;


-ms-transition: all 0.30s ease-in-out;


transition: all 0.30s ease-in-out;


&[type="text"]:hover, &[type="email"]:hover, &[type="password"]:hover {


background: #fafafa;


&[type="text"]:focus, &[type="email"]:focus, &[type="password"]:focus {


-webkit-box-shadow: 0 0 2px 1px rgba(255, 169, 0, 0.5);


-moz-box-shadow: 0 0 2px 1px rgba(255, 169, 0, 0.5);


box-shadow: 0 0 2px 1px rgba(255, 169, 0, 0.5);


border: 1px solid $yellow;


background: #fafafa;


&[type="submit"] {


background: $yellow;


height: 35px;


line-height: 35px;


width: 100%;


border: none;


outline: none;


cursor: pointer;


color: #fff;


font-size: 1.1em;


margin-bottom: 10px;


-webkit-transition: all 0.30s ease-in-out;


-moz-transition: all 0.30s ease-in-out;


-ms-transition: all 0.30s ease-in-out;


transition: all 0.30s ease-in-out;


&:hover {


background: darken($yellow,7%);


&:focus {


background: darken($yellow,7%);


&[type="checkbox"], &[type="radio"] {


border: 0;


clip: rect(0 0 0 0);


height: 1px;


margin: -1px;


overflow: hidden;


padding: 0;


position: absolute;


width: 1px;


.form_container {


.row {


.col_half.last {


border-left: 1px solid $grey;


@-webkit-keyframes check {


0% { height: 0; width: 0; }


25% { height: 0; width: 7px; }


50% { height: 20px; width: 7px; }


@keyframes check {


0% { height: 0; width: 0; }


25% { height: 0; width: 7px; }


50% { height: 20px; width: 7px; }


@-webkit-keyframes expand {


0% { -webkit-transform: scale3d(1,0,1); opacity:0; }


25% { -webkit-transform: scale3d(1,1.2,1); }


50% { -webkit-transform: scale3d(1,0.85,1); }


75% { -webkit-transform: scale3d(1,1.05,1); }


100% { -webkit-transform: scale3d(1,1,1); opacity:1; }


@keyframes expand {


0% { -webkit-transform: scale3d(1,0,1); transform: scale3d(1,0,1); opacity:0; }


25% { -webkit-transform: scale3d(1,1.2,1); transform: scale3d(1,1.2,1); }


50% { -webkit-transform: scale3d(1,0.85,1); transform: scale3d(1,0.85,1); }


75% { -webkit-transform: scale3d(1,1.05,1); transform: scale3d(1,1.05,1); }


100% { -webkit-transform: scale3d(1,1,1); transform: scale3d(1,1,1); opacity:1; }


@-webkit-keyframes bounce {


0% { -webkit-transform: translate3d(0,-25px,0); opacity:0; }


25% { -webkit-transform: translate3d(0,10px,0); }


50% { -webkit-transform: translate3d(0,-6px,0); }


75% { -webkit-transform: translate3d(0,2px,0); }


100% { -webkit-transform: translate3d(0,0,0); opacity: 1; }


@keyframes bounce {


0% { -webkit-transform: translate3d(0,-25px,0); transform: translate3d(0,-25px,0); opacity:0; }


25% { -webkit-transform: translate3d(0,10px,0); transform: translate3d(0,10px,0); }


50% { -webkit-transform: translate3d(0,-6px,0); transform: translate3d(0,-6px,0); }


75% { -webkit-transform: translate3d(0,2px,0); transform: translate3d(0,2px,0); }


100% { -webkit-transform: translate3d(0,0,0); transform: translate3d(0,0,0); opacity: 1; }


@media (max-width: 600px) {


.form_wrapper {


.col_half {


width: 100%;


float: none;


.bottom_row {


.col_half {


width: 50%;


float: left;




style


body


div


class


"form_wrapper"


div


class


"form_container"


div


class


"title_container"


h1


>GeekUser Registration Form


h1


form


action


"register"


method


"post"


table


cellpadding


"3pt"


tr


td


>User Name :


td


td


><


input


type


"text"


name


"userName"


size


"50"


/>


td




tr


tr


td


>Password :


td


td


><


input


type


"password"


name


"password1"


size


"50"


/>


td




tr


tr


td


>Confirm Password :


td


td


><


input


type


"password"


name


"password2"


size


"50"


/>


td




tr


tr


td


>email :


td


td


><


input


type


"text"


name


"email"


size


"50"


/>


td




tr


tr


td


>Phone :


td


td


><


input


type


"text"


name


"phone"


size


"50"


/>


td




tr


tr


td


>City :


td


td


><


input


type


"text"


name


"city"


size


"50"


/>


td




tr




table


/>


input


type


"submit"


value


"Register"


/>




form




div




div




div




body




html

Web Application with Hibernate (using XML)

Here, we are going to create a web application with hibernate. For creating the web application, we are using JSP for presentation logic, Bean class for representing data and DAO class for database codes.

As we create the simple application in hibernate, we don’t need to perform any extra operations in hibernate for creating web application. In such case, we are getting the value from the user using the JSP file.

Example to create web application using hibernate

In this example, we are going to insert the record of the user in the database. It is simply a registration form.

index.jsp

This page gets input from the user and sends it to the register.jsp file using post method.

register.jsp

This file gets all request parameters and stores this information into an object of User class. Further, it calls the register method of UserDao class passing the User class object.

User.java

It is the simple bean class representing the Persistent class in hibernate.

user.hbm.xml

It maps the User class with the table of the database.

UserDao.java

A Dao class, containing method to store the instance of User class.

hibernate.cfg.xml

It is a configuration file, containing informations about the database and mapping file.

Output
Download

Next TopicGenerator Classes

Using Hibernate in a Web Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Web Application Project
  • Modifying the Hibernate Configuration File
  • Creating the

    HibernateUtil.java

    Helper File
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the

    FilmHelper.java

    Helper Class
  • Creating the JSF Managed Bean
  • Creating the Web Pages
  • Running the Project
  • See Also

In this tutorial, you use the NetBeans IDE to create and deploy a web application that displays data from a database. The web application uses the Hibernate framework as the persistence layer for retrieving and storing plain old Java objects (POJOs) to a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates how to add support for the Hibernate framework to the IDE and create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a JSF managed bean and JSF 2.0 pages to display the data.

Before starting this tutorial you may want to familiarize yourself with the following documents.

  • Hibernate documentation at hibernate.org

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.1, 7.2, 7.3, 7.4, Java EE version

Version 6 or 7

GlassFish Server Open Source Edition

3.x or 4.x

Version 5.x

Sakila Database

Plugin available from update center

You can download a zip archive of the finished project.

Create Application Class

Finally, we will create our application class with the main() method to run the application. We will use this application to save few Employee’s records and then we will apply CRUD operations on those records.

import java.util.List; import java.util.Date; import java.util.Iterator; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class ManageEmployee { private static SessionFactory factory; public static void main(String[] args) { try { factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println(“Failed to create sessionFactory object.” + ex); throw new ExceptionInInitializerError(ex); } ManageEmployee ME = new ManageEmployee(); /* Add few employee records in database */ Integer empID1 = ME.addEmployee(“Zara”, “Ali”, 1000); Integer empID2 = ME.addEmployee(“Daisy”, “Das”, 5000); Integer empID3 = ME.addEmployee(“John”, “Paul”, 10000); /* List down all the employees */ ME.listEmployees(); /* Update employee’s records */ ME.updateEmployee(empID1, 5000); /* Delete an employee from the database */ ME.deleteEmployee(empID2); /* List down new list of the employees */ ME.listEmployees(); } /* Method to CREATE an employee in the database */ public Integer addEmployee(String fname, String lname, int salary){ Session session = factory.openSession(); Transaction tx = null; Integer employeeID = null; try { tx = session.beginTransaction(); Employee employee = new Employee(fname, lname, salary); employeeID = (Integer) session.save(employee); tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } return employeeID; } /* Method to READ all the employees */ public void listEmployees( ){ Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); List employees = session.createQuery(“FROM Employee”).list(); for (Iterator iterator = employees.iterator(); iterator.hasNext();){ Employee employee = (Employee) iterator.next(); System.out.print(“First Name: ” + employee.getFirstName()); System.out.print(” Last Name: ” + employee.getLastName()); System.out.println(” Salary: ” + employee.getSalary()); } tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } } /* Method to UPDATE salary for an employee */ public void updateEmployee(Integer EmployeeID, int salary ){ Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); employee.setSalary( salary ); session.update(employee); tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } } /* Method to DELETE an employee from the records */ public void deleteEmployee(Integer EmployeeID){ Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Employee employee = (Employee)session.get(Employee.class, EmployeeID); session.delete(employee); tx.commit(); } catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); } finally { session.close(); } } }

Spring Boot & Spring Data JPA – Complete Course
Spring Boot & Spring Data JPA – Complete Course

Web Application With Hibernate,JSP and Servlet using Eclipse

Hibernate integration with Servlet and JSP :

In this tutorial, we are going to create a web application with hibernate. We are going to insert the record of the user in the database.We will create Registration form for getting user data.These data we will collect in servlet and finally insert these data into Database by using hibernate.

For creating the web application, we are using JSP for presentation logic, Servlet class for controller layer and DAO class for database access codes.

Tools and Technologies :

  • JDK
  • Hibernate 3.6.3.Final
  • Eclipse
  • MySQL 5.5.
  • Tomcat

Follow the steps mentioned below to create this example.

Step 1 : Create Dynamic Web Project :

Open eclipse IDE,and go to

File -> New -> Project ->

and select

Dynamic Web Project

,specify the project name as HibernateWebApp and click on next -> finish .

Step 2 : Add Jar files for hibernate and mysql :

Copy all the jar files as shown below inside lib folder of the project

Step 3 : Creating web pages :

Now let us create register.jsp file inside Web-Content folder of your project.This is a simple form where user can provide his/her detail.

Right Click on Web-Content then New -> JSP File and provide the name of JSP file as register.jsp and click Finish.

Add following code in this file

register.jsp

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>













Registration Form


	

Registration Form

User Name :
Password :
Confirm Password :
email :
Phone :
City :

Step 4 : Creating Java Classes :

Create a package com.jwt.hibernate.controller and create a java class UserControllerServlet in this package and add following code in this class.

UserControllerServlet.java

package com.jwt.hibernate.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jwt.hibernate.dao.UserDAO;

public class UserControllerServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userName");
		String password = request.getParameter("password1");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String city = request.getParameter("city");

		HttpSession session = request.getSession(true);
		try {
			UserDAO userDAO = new UserDAO();
			userDAO.addUserDetails(userName, password, email, phone, city);
			response.sendRedirect("Success");
		} catch (Exception e) {

			e.printStackTrace();
		}

	}
}

Above class is controller class for our application.In this class we are collecting the data from user and storing the data by calling UserDAO class addUserDetails method.If the database insertion is successful request will be forwarded to Success.java Servlet class.

User.java

This is a simple bean class representing the Persistent class in hibernate.

Create a package com.jwt.hibernate.bean,in this package create java class User.java and add following code in this class.


package com.jwt.hibernate.bean;

public class User {
	private int id;
	private String userName;
	private String password1;
	private String email;
	private String phone;
	private String city;

	public int getId() {
		return id;
	}

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

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword1() {
		return password1;
	}

	public void setPassword1(String password1) {
		this.password1 = password1;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

}
UserDAO.java

This is DAO class. In this class we have implemented addUserDetails() method where we are adding the user details to database by using hibernate.

Create a package com.jwt.hibernate.dao,in this package create java class UserDAO.java and add following code in this class.


package com.jwt.hibernate.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.jwt.hibernate.bean.User;

public class UserDAO {

	public void addUserDetails(String userName, String password, String email,
			String phone, String city) {
		try {
			// 1. configuring hibernate
			Configuration configuration = new Configuration().configure();

			// 2. create sessionfactory
			SessionFactory sessionFactory = configuration.buildSessionFactory();

			// 3. Get Session object
			Session session = sessionFactory.openSession();

			// 4. Starting Transaction
			Transaction transaction = session.beginTransaction();
			User user = new User();
			user.setUserName(userName);
			user.setPassword1(password);
			user.setEmail(email);
			user.setCity(city);
			user.setPhone(phone);
			session.save(user);
			transaction.commit();
			System.out.println("\n\n Details Added \n");

		} catch (HibernateException e) {
			System.out.println(e.getMessage());
			System.out.println("error");
		}

	}

}
Success.java

User will be redirected to this class after successful insertion of data.


package com.jwt.hibernate.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Success extends HttpServlet {

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();

		writer.println("" + "" + ""
				+ "Details Added Successfully" + "" + ""
				+ "");
	}

}

Step 5 : Create the mapping file :

Mapping file maps the User class with the table of the database.

Right click on com.jwt.hibernate.bean then navigate to

New -> Other -> General -> Next

and provide the name of file as

user.hbm.xml

and click on finish.After creating user.hbm.xml add following code in this file.

user.hbm.xml

Step 6 : Create the Configuration file :

The configuration file contains informations about the database and mapping file. Conventionally, its name should be hibernate.cfg.xml .Configuration file must be in classpath of your Project.Place this file in src of your project by default it will added to classpath of your project.

hibernate.cfg.xml













	
		com.mysql.jdbc.Driver
		jdbc:mysql://localhost:3306/jwt
		root
		mukesh
		org.hibernate.dialect.MySQLDialect
		true
		true
		create 
		
	

Step 7: Create web.xml file :

Create web.xml file inside WEB-INF directory of project.

web.xml



	HibernateWebApp
	
		User
		User
		com.jwt.hibernate.controller.UserControllerServlet
	
	
		Success
		Success
		com.jwt.hibernate.controller.Success
	
	
		User
		/register
	
	
		Success
		/Success
	
	
		register.jsp
	

Directory structure of the project :

Directory Structure of the project is given bellow.

Run the Application :

To run the hibernate web application, right click on the project then Run as -> Run On Server select Tomcat -> Next ->Finish.

Output in Browser :

Fill the form and click on submit button :

If everything is fine and data is inserted into table user will be redirected to Success page as shown below :

Check the data in the Database :

After submitting the data USER table is created by Hibernate and data is inserted into this table as shown above :

You can download the source code of the example by clicking on the Download link below.


Download


Previous


Next Article

In the previous article, we have seen JSP Servlet JDBC MySQL CRUD Example Tutorial.In this article, we will learn step-by-step how to build a User Management web application using JSP, Servlet, Hibernate, and MySQL database. In this article, we will use Hibernate Java-based configuration without using XML-based configuration(hibernate.cfg.xml) to connect to the MySQL database.

In this article, we will learn step-by-step how to build a User Management web application using JSP, Servlet, Hibernate, and MySQL database. In this article, we will use Hibernate Java-based configuration without using XML-based configuration(hibernate.cfg.xml) to connect to the MySQL database.

Before deep dive into building web applications, let’s quickly recap what is JSP, Servlet, Hibernate, and the MySQL database.

JSP (JavaServer Pages)

JSP stands for JavaServer Pages. It’s a technology used for building dynamic web content. Unlike static HTML, JSP allows you to embed Java code and expressions directly within your HTML code. This ability to mix Java with HTML enables developers to create dynamic web pages that can change content, appearance, and behavior based on user input or other interactions.

Learn everything about JSP here at JSP Tutorial

Servlets

A Servlet is a Java class used in web development to handle HTTP requests and responses. It acts as a middleman between the client’s request from a web browser and the server’s response.

Servlets can be used to process forms, control the flow of an application, and generate dynamic content. They form an essential part of the Java EE (Enterprise Edition) specification and provide a robust, scalable solution for web development.

Learn everything about Servlets here at Servlet Tutorial

Hibernate

Hibernate is an Object-Relational Mapping (ORM) framework for Java. It simplifies database interaction by allowing developers to use regular Java objects to represent database tables. This means that you can write Java code to interact with your database, rather than writing complex SQL queries.

Hibernate takes care of translating these Java interactions into the necessary database commands, allowing for more portable and maintainable code.

Learn everything about Servlets here at Hibernate Tutorial

MySQL Database

MySQL is one of the most popular open-source relational database management systems (RDBMS) in the world. It uses Structured Query Language (SQL) to access, manipulate, and manage data stored in relational databases.

MySQL is known for its speed, reliability, and ease of use. It’s used by many large-scale websites and applications to store and manage data in a structured and efficient way.

JSP Servlet Hibernate Web Application

  1. Create a User
  2. Update a User
  3. Delete a User
  4. Retrieve a User
  5. List of all Users

Tools and technologies used

  • JSP
  • Hibernate
  • IDE – STS/Eclipse
  • JDK – 1.8 or later
  • Apache Tomcat
  • JSTL
  • Servlet API
  • MySQL

Development Steps

  1. Create an Eclipse Dynamic Web Project
  2. Add Dependencies
  3. Project Structure
  4. MySQL Database Setup
  5. Create a JPA entity – User.java
  6. Hibernate Java-based configuration
  7. Create a UserDAO.java
  8. Create a UserServlet.java
  9. Creating User Listing JSP Page – user-list.jsp
  10. Create a User Form JSP Page – user-form.jsp
  11. Creating Error JSP page
  12. Deploying and Testing the Application Demo

Create an Eclipse Dynamic Web Project

To create a new dynamic Web project in Eclipse:

1. On the main menu select File > New > Project….

2. In the upcoming wizard choose Web > Dynamic Web Project.

3. Click Next.

4. Enter project name as “jsp-servlet-hibernate-mysql-example”;

5. Make sure that the target runtime is set to Apache Tomcat with the currently supported version.

Add Dependencies

Add the latest release of the below jar files to the lib folder:

You can download all these JAR files from my GitHub repository – jsp-servlet-hibernate-mysql-tutorial

MySQL Database Setup

Let’s create a database named “demo” in MySQL. Now, create a users table using below DDL script:

CREATE DATABASE ‘demo’; USE demo; create table users ( id int(3) NOT NULL AUTO_INCREMENT, name varchar(120) NOT NULL, email varchar(220) NOT NULL, country varchar(120), PRIMARY KEY (id) );

You can use either MySQL Command Line Client or MySQL Workbench tool to create the database. The above users table looks like this:

Create a JPA Entity – User.java

Let’s create a User JPA entity that is mapped to a database table – users.

package net.javaguides.usermanagement.model; import javax.persistence.*; /** * User.java * This is a model class represents a User entity * @author Ramesh Fadatare * */ @Entity @Table(name=”users”) public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name=”id”) protected int id; @Column(name=”name”) protected String name; @Column(name=”email”) protected String email; @Column(name=”country”) protected String country; public User() { } public User(String name, String email, String country) { super(); this.name = name; this.email = email; this.country = country; } public User(int id, String name, String email, String country) { super(); this.id = id; this.name = name; this.email = email; this.country = country; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }

Let’s understand the annotations used in the above class:

@Entity: This annotation indicates that the class is a JPA entity, meaning that it will be mapped to a database table.

@Table: This specifies the name of the table in the database to which this entity will be mapped. In this case, the table name is “users”

@Id: This marks the field as the primary key for the database table.

@GeneratedValue(strategy=GenerationType.IDENTITY): This specifies how the primary key will be generated. The IDENTITY strategy means that the database will generate a new value for each insert.

@Column: This annotation map the field to the corresponding column in the database table, allowing custom column name and its attributes.

Hibernate Java-based configuration

The below diagram shows Java code for Hibernate settings equivalent to hibernate.cfg.xml properties:

Open HibernateUtil class and add the following code to it:

package net.javaguides.usermanagement.utl; import java.util.Properties; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; import net.javaguides.usermanagement.model.User; /** * Java based configuration * @author ramesh Fadatare * */ public class HibernateUtil { private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { if (sessionFactory == null) { try { Configuration configuration = new Configuration(); // Hibernate settings equivalent to hibernate.cfg.xml’s properties Properties settings = new Properties(); settings.put(Environment.DRIVER, “com.mysql.jdbc.Driver”); settings.put(Environment.URL, “jdbc:mysql://localhost:3306/demo?useSSL=false”); settings.put(Environment.USER, “root”); settings.put(Environment.PASS, “root”); settings.put(Environment.DIALECT, “org.hibernate.dialect.MySQL5Dialect”); settings.put(Environment.SHOW_SQL, “true”); settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, “thread”); settings.put(Environment.HBM2DDL_AUTO, “create-drop”); configuration.setProperties(settings); configuration.addAnnotatedClass(User.class); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); System.out.println(“Hibernate Java Config serviceRegistry created”); sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Exception e) { e.printStackTrace(); } } return sessionFactory; } }

The Configuration object is used to configure Hibernate settings. In this code, settings are applied programmatically using the Properties object, which is equivalent to setting them in the hibernate.cfg.xml file.

The configuration.addAnnotatedClass(User.class) method call adds the User class as an entity, allowing Hibernate to map it to a database table.

The ServiceRegistry is responsible for holding and managing services that Hibernate uses. It’s constructed with the settings from the Configuration object.

Create a UserDAO.java

Let’s create a UserDAO class which is a Data Access Layer (DAO) class that provides CRUD (Create, Read, Update, Delete) operations using for the users table in a database using Hibernate. Here’s the full source code of the UserDAO:

The saveUser(User user) saves a User object to the database.

package net.javaguides.usermanagement.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.Transaction; import net.javaguides.usermanagement.model.User; import net.javaguides.usermanagement.utl.HibernateUtil; /** * CRUD database operations * @author Ramesh Fadatare * */ public class UserDao { /** * Save User * @param user */ public void saveUser(User user) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // save the student object session.save(user); // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } /** * Update User * @param user */ public void updateUser(User user) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // save the student object session.update(user); // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } /** * Delete User * @param id */ public void deleteUser(int id) { Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // Delete a user object User user = session.get(User.class, id); if (user != null) { session.delete(user); System.out.println(“user is deleted”); } // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } /** * Get User By ID * @param id * @return */ public User getUser(int id) { Transaction transaction = null; User user = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // get an user object user = session.get(User.class, id); // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } return user; } /** * Get all Users * @return */ @SuppressWarnings(“unchecked”) public List < User > getAllUser() { Transaction transaction = null; List < User > listOfUser = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // get an user object listOfUser = session.createQuery(“from User”).getResultList(); // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } return listOfUser; } }

The updateUser(User user) updates an existing User object in the database.

The deleteUser(int id) deletes a User object from the database by its ID.

The getUser(int id) retrieves a User object from the database by its ID

The getAllUser() retrieves all User objects from the database.

Create a UserServlet.java

Now, let’s create a UserServlet that acts as a page controller to handle all requests from the client.

Let’s look at the code first:

Let’s understand the above code:

package net.javaguides.usermanagement.web; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.RequestDispatcher; 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 net.javaguides.usermanagement.dao.UserDao; import net.javaguides.usermanagement.model.User; /** * ControllerServlet.java * This servlet acts as a page controller for the application, handling all * requests from the user. * @email Ramesh Fadatare */ @WebServlet(“/”) public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; private UserDao userDao; public void init() { userDao = new UserDao(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getServletPath(); try { switch (action) { case “/new”: showNewForm(request, response); break; case “/insert”: insertUser(request, response); break; case “/delete”: deleteUser(request, response); break; case “/edit”: showEditForm(request, response); break; case “/update”: updateUser(request, response); break; default: listUser(request, response); break; } } catch (SQLException ex) { throw new ServletException(ex); } } private void listUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException { List < User > listUser = userDao.getAllUser(); request.setAttribute(“listUser”, listUser); RequestDispatcher dispatcher = request.getRequestDispatcher(“user-list.jsp”); dispatcher.forward(request, response); } private void showNewForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher dispatcher = request.getRequestDispatcher(“user-form.jsp”); dispatcher.forward(request, response); } private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException { int id = Integer.parseInt(request.getParameter(“id”)); User existingUser = userDao.getUser(id); RequestDispatcher dispatcher = request.getRequestDispatcher(“user-form.jsp”); request.setAttribute(“user”, existingUser); dispatcher.forward(request, response); } private void insertUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException { String name = request.getParameter(“name”); String email = request.getParameter(“email”); String country = request.getParameter(“country”); User newUser = new User(name, email, country); userDao.saveUser(newUser); response.sendRedirect(“list”); } private void updateUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException { int id = Integer.parseInt(request.getParameter(“id”)); String name = request.getParameter(“name”); String email = request.getParameter(“email”); String country = request.getParameter(“country”); User user = new User(id, name, email, country); userDao.updateUser(user); response.sendRedirect(“list”); } private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException { int id = Integer.parseInt(request.getParameter(“id”)); userDao.deleteUser(id); response.sendRedirect(“list”); } }

UserServlet extends HttpServlet, making it capable of handling HTTP requests.

The @WebServlet(“/”) annotation maps this servlet to the root URL path of the application.

The servlet initializes an instance of UserDao, which is likely a DAO (Data Access Object) class responsible for database interactions related to user management.

The doPost() method redirects POST requests to the doGet method.

The doGet() method handles GET requests by switching on the servlet path and calling the appropriate method for various user-related actions (e.g., showing a new form, inserting a user, deleting a user, etc.).

Creating User Listing JSP Page – user-list.jsp

Next, create a JSP page for displaying all users from the database.

Let’s create a list-user.jsp page under the WebContent directory in the project with the following code:

<%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%> <%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>

<br /> User Management Application<br />


User Management

Generating Hibernate Mapping Files and Java Classes

In this tutorial you use a POJO (plain old Java object) to represent the data in each of the tables in the database that you will use. The Java class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map the POJOs to the tables you can use a Hibernate mapping file or use annotations in the class.

You can use the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables. When you use the wizard you select all the tables for which you want POJOs and mapping files and the IDE then generates the files for you based on the database tables and adds the mapping entries to

hibernate.cfg.xml

. When you use the wizard you can choose the files that you want the IDE to generate (only the POJOs, for example) and select code generation options (generate code that uses EJB 3 annotations, for example).

Note. The IDE also has wizards to help you create individual POJOs and mapping files from scratch.

Creating the Hibernate Reverse Engineering File

If you want to use the Hibernate Mapping Files and POJOs from a Database wizard, you first need to create a

hibernate.reveng.xml

reverse engineering file. The Hibernate Mapping Files and POJOs from a Database wizard requires

hibernate.reveng.xml

and

hibernate.cfg.xml

.

The reverse engineering file enables you to have greater control over the database mapping strategy. The Hibernate Reverse Engineering Wizard creates a reverse engineering file with a default configuration that you can edit in the XML editor.

To create the Hibernate reverse engineering file, perform the following steps.

  1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Hibernate Reverse Engineering Wizard in the Hibernate category. Click Next.

  3. Specify


    hibernate.reveng

    as the File Name and

    src/java

    for the Folder. Click Next.

  4. Select


    hibernate.cfg.xml

    from the Configuration File drop down list, if not selected.

  5. Select the following tables from Available Tables and click Add to add the tables to Selected Tables.

    • actor

    • category

    • film

    • film_actor

    • film_category

    • language

Click Finish.

The wizard generates a

hibernate.reveng.xml

reverse engineering file and opens the file in the editor. You can close the reverse engineering file because you will not need to edit the file.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Controlling reverse engineering in the Hibernate Tools Reference Guide.

Creating the Hibernate Mapping Files and POJOs

You can use the Hibernate Mapping Files and POJOs from a Database wizard to generate files for you. The wizard can generate a POJO and a corresponding mapping file for each table that you select in the wizard. The mapping files are XML files that contain data about how the columns in the tables are mapped to the fields in the POJOs. You need to have the

hibernate.reveng.xml

and

hibernate.cfg.xml

files to use the wizard.

To create the POJOS and mapping files using a wizard, perform the following steps.

  1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Hibernate Mapping Files and POJOs from a Database in the Hibernate category. Click Next.

  3. Ensure that the


    hibernate.cfg.xml

    and

    hibernate.reveng.xml

    files are selected in the drop down lists.

  4. Select JDK 5 Language Features under the General Settings options.

  5. Ensure that the Domain Code and Hibernate XML Mappings options are selected.

  6. Select dvdrental for the Package name. Click Finish.

When you click Finish the IDE generates POJOs and Hibernate mapping files with the fields mapped to the columns specified in

hibernate.reveng.xml

. The IDE also adds mapping entries to

hibernate.cfg.xml

.



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila myusername mypassword true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory

Note. Confirm that the

mapping

elements are listed after the

property

elements in the

hibernate.cfg.xml

file.

You can expand the

dvdrental

package to see the files generated by the wizard.

You can use the Hibernate Mapping wizard if you want to create a Hibernate mapping file that maps a specific table to a specific class.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Basic O/R Mapping in the Hibernate Reference Documentation.

JPA And Hibernate Tutorial For Beginners with Spring Boot and Spring Data JPA
JPA And Hibernate Tutorial For Beginners with Spring Boot and Spring Data JPA

Wrapping up

Refer:

Hibernate Annotations Example

https://stackoverflow.com/questions/44248528/what-is-the-maven-dependency-for-java-ee7-and-cdi-2-0

https://www.baeldung.com/ejb-session-beans

https://dzone.com/articles/in-practice-dependency-injection-with-java-ee

https://stackoverflow.com/questions/7297565/javassist-what-is-the-main-idea-and-where-real-use

Problem about encoding in database

https://stackoverflow.com/questions/13063372/hibernate-mysql-how-to-set-the-encoding-utf-8-for-database-and-tables

https://makandracards.com/makandra/2529-show-and-change-mysql-default-character-set

JDBC Driver Connection URL strings

Web Application with Hibernate (using XML)

Here, we are going to create a web application with hibernate. For creating the web application, we are using JSP for presentation logic, Bean class for representing data and DAO class for database codes.

As we create the simple application in hibernate, we don’t need to perform any extra operations in hibernate for creating web application. In such case, we are getting the value from the user using the JSP file.

Example to create web application using hibernate

In this example, we are going to insert the record of the user in the database. It is simply a registration form.

index.jsp

This page gets input from the user and sends it to the register.jsp file using post method.

register.jsp

This file gets all request parameters and stores this information into an object of User class. Further, it calls the register method of UserDao class passing the User class object.

User.java

It is the simple bean class representing the Persistent class in hibernate.

user.hbm.xml

It maps the User class with the table of the database.

UserDao.java

A Dao class, containing method to store the instance of User class.

hibernate.cfg.xml

It is a configuration file, containing informations about the database and mapping file.

Output
Download

Next TopicGenerator Classes

Web Application With Hibernate,JSP and Servlet using Eclipse

Creating the Database

This tutorial uses a MySQL database called

sakila

, a free sample MySQL database that is available from the MySQL site. The sakila database is not included when you install the IDE so you need to first create the database to follow this tutorial.

To create the sakila database you can download and install the Sakila Sample Database plugin using the Plugins manager. After you install the plugin the sakila database is added to the list of databases in the Create MySQL database dialog box.

For more information on configuring the IDE to work with MySQL, see the Connecting to a MySQL Database tutorial.

  1. Open the Plugins manager and install the Sakila Sample Database plugin.

  2. After installing the plugin, start the MySQL database by expanding the Databases node in the Services window, right-clicking the MySQL Server node and choosing Start.

  3. Right-click the MySQL Server node and choose Create Database.

  4. Select the Sakila database from the New Database Name drop down list in the Create MySQL Database dialog box. Click OK.

When you click OK a Sakila node appears under the MySQL Server node.

  1. Right-click the Sakila node and choose Connect.

When you click Connect a database connection node for the Sakila database (

jdbc:mysql://localhost:3306/sakila [username on Default]

) is listed under the Databases node. When a connection is open you can view the data in the database by expanding the connection node.

Spring Framework: A Tutorial for Beginners | in28minutes | Ranga Karanam
Spring Framework: A Tutorial for Beginners | in28minutes | Ranga Karanam

Preparing database in MySQL

In order to implement the communication between MySQL and Hibernate, we need to create our own database in MySQL. The following is the content of sql file that is used to create database and table

Employee

.


CREATE DATABASE java_sql; USE java_sql; CREATE TABLE `EMPLOYEE` ( ID INT NOT NULL AUTO_INCREMENT, FULL_NAME VARCHAR(20) DEFAULT NULL, AGE INT DEFAULT NULL, PRIMARY KEY (ID) ); INSERT INTO `employee` (ID, FULL_NAME, AGE) VALUES (1, "John", 56), (2, "Bill Adam", 45), (3, "Mary Smith", 78); SELECT * FROM `employee`;

Fix some problems

  • If we modify Hibernate from EclipseLink, with one-to-one relationship or one-to-many relationship, we have error such as:


    Multiple writable mappings exist for the field []. Only one may be defined as writable, all others must be specified read-only.

    Source code for this problem:


    public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String email; private String password; private int reputation; @OneToOne(mappedBy="user", cascade={CascadeType.ALL}) private Company company; @OneToOne(mappedBy="user") private Person person; ... } @Entity public class Person implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id_user") private int idUser; @Temporal( TemporalType.DATE) private Date birthdate; private String gender; private String name; private String surname; @OneToOne @JoinColumn(name="id_user", insertable=false, updatable=false) private User user; } public class Company implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id_user") private int idUser; private String email; private String name; @ManyToOne @JoinColumn(name="area") private Area areaBean; @OneToOne(cascade={CascadeType.ALL}) @JoinColumn(name="id_user", insertable=false, updatable=false) private User user; }

    The reason for this error: we have the


    id_user

    column mapped twice, once using a basic

    @Id

    mapping, and once using the

    @ManyToOne

    . We need to make one of them readonly, such as

    insertable=false

    ,

    updatable=false

    in

    @JoinColumn

    annotation. Or better just remove the basic id, and put the

    @Id

    on the

    @ManyToOne

    .

    So, we have two way to solve this error:

    • Replace

      @JoinColumn(name="area")

      as

      @PrimaryKeyColumn(name = "area", referencedColumnName = "id")

      .
    • Placing the

      insertable=false

      ,

      updatable=false

      in the

      @JoinColumn

      annotation in both classes,

      Person

      and

      Company

      .

    We can reference to this link.

  • Replace
Hibernate Tutorial For Beginners | Java Hibernate in 100 minutes | Hibernate Project | Simplilearn
Hibernate Tutorial For Beginners | Java Hibernate in 100 minutes | Hibernate Project | Simplilearn

Modifying the Hibernate Configuration File

When you create a new project that uses the Hibernate framework, the IDE automatically creates the

hibernate.cfg.xml

configuration file at the root of the context classpath of the application (in the Files window,

src/java

). The file is located in the under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise you will edit the default properties specified in

hibernate.cfg.xml

to enable debug logging for SQL statements and to enable Hibernate’s session context management.

  1. Open


    hibernate.cfg.xml

    in the Design tab. You can open the file by expanding thenode under Source Packages in the Projects window and double-clicking

    hibernate.cfg.xml

    .

  2. In the multi-view XML editor, expand the Configuration Properties node under Optional Properties.

  3. Click Add to open the Add Hibernate Property dialog box.

  4. In the dialog box, select the


    hibernate.show_sql

    property and set the value to

    true

    . This enables the debug logging of the SQL statements.

  1. Expand the Miscellaneous Properties node and click Add.

  2. In the dialog box, select the


    properties hibernate.current_session_context_class

    and set the value to

    thread

    to enable Hibernate’s automatic session context management.

  1. Click Add again under the Miscellaneous Properties node and select


    hibernate.query.factory_class

    in the Property Name dropdown list.

  2. Select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value. Click OK.

If you click the XML tab in the editor you can see the file in XML view. Your file should look similar to the following (the three new properties are bold):



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### * true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory *


  1. Save your changes to the file.

You can close the file because you do not need to edit the file again.

Generating Hibernate Mapping Files and Java Classes

In this tutorial you use a POJO (plain old Java object) to represent the data in each of the tables in the database that you will use. The Java class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map the POJOs to the tables you can use a Hibernate mapping file or use annotations in the class.

You can use the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables. When you use the wizard you select all the tables for which you want POJOs and mapping files and the IDE then generates the files for you based on the database tables and adds the mapping entries to

hibernate.cfg.xml

. When you use the wizard you can choose the files that you want the IDE to generate (only the POJOs, for example) and select code generation options (generate code that uses EJB 3 annotations, for example).

Note. The IDE also has wizards to help you create individual POJOs and mapping files from scratch.

Creating the Hibernate Reverse Engineering File

If you want to use the Hibernate Mapping Files and POJOs from a Database wizard, you first need to create a

hibernate.reveng.xml

reverse engineering file. The Hibernate Mapping Files and POJOs from a Database wizard requires

hibernate.reveng.xml

and

hibernate.cfg.xml

.

The reverse engineering file enables you to have greater control over the database mapping strategy. The Hibernate Reverse Engineering Wizard creates a reverse engineering file with a default configuration that you can edit in the XML editor.

To create the Hibernate reverse engineering file, perform the following steps.

  1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Hibernate Reverse Engineering Wizard in the Hibernate category. Click Next.

  3. Specify


    hibernate.reveng

    as the File Name and

    src/java

    for the Folder. Click Next.

  4. Select


    hibernate.cfg.xml

    from the Configuration File drop down list, if not selected.

  5. Select the following tables from Available Tables and click Add to add the tables to Selected Tables.

    • actor

    • category

    • film

    • film_actor

    • film_category

    • language

Click Finish.

The wizard generates a

hibernate.reveng.xml

reverse engineering file and opens the file in the editor. You can close the reverse engineering file because you will not need to edit the file.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Controlling reverse engineering in the Hibernate Tools Reference Guide.

Creating the Hibernate Mapping Files and POJOs

You can use the Hibernate Mapping Files and POJOs from a Database wizard to generate files for you. The wizard can generate a POJO and a corresponding mapping file for each table that you select in the wizard. The mapping files are XML files that contain data about how the columns in the tables are mapped to the fields in the POJOs. You need to have the

hibernate.reveng.xml

and

hibernate.cfg.xml

files to use the wizard.

To create the POJOS and mapping files using a wizard, perform the following steps.

  1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Hibernate Mapping Files and POJOs from a Database in the Hibernate category. Click Next.

  3. Ensure that the


    hibernate.cfg.xml

    and

    hibernate.reveng.xml

    files are selected in the drop down lists.

  4. Select JDK 5 Language Features under the General Settings options.

  5. Ensure that the Domain Code and Hibernate XML Mappings options are selected.

  6. Select dvdrental for the Package name. Click Finish.

When you click Finish the IDE generates POJOs and Hibernate mapping files with the fields mapped to the columns specified in

hibernate.reveng.xml

. The IDE also adds mapping entries to

hibernate.cfg.xml

.



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila myusername mypassword true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory

Note. Confirm that the

mapping

elements are listed after the

property

elements in the

hibernate.cfg.xml

file.

You can expand the

dvdrental

package to see the files generated by the wizard.

You can use the Hibernate Mapping wizard if you want to create a Hibernate mapping file that maps a specific table to a specific class.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Basic O/R Mapping in the Hibernate Reference Documentation.

Spring Boot Thymeleaf Web Application | Full Course ✅ | Student Management System Project
Spring Boot Thymeleaf Web Application | Full Course ✅ | Student Management System Project

Table of content

  • Creating project using Maven
  • Preparing database in MySQL
  • Add dependencies of Maven to pom.xml file
  • Configuring xml file for Hibernate
  • Creating entity that is corresponding to a table in MySQL
  • Creating CRUD operations to MySQL
  • Fix some problems
  • Wrapping up

Creating the FilmHelper.java Helper Class

You will now create a helper class in the

dvdrental

package that will be used to perform Hibernate queries on the database. You will use the Hibernate Query Language (HQL) editor to construct and test the queries for retrieving data. After you test the queries you will create methods in the helper class that construct and run the queries. You will then invoke the methods in the helper class from a JSF managed bean.

Creating the Class

In this section you use the New File wizard to create the helper class

FilmHelper.java

in the

dvdrental

package. You will create a Hibernate session by calling

getSessionFactory

in

HibernateUtil.java

and create some helper methods to create queries to retrieve data from the database. You will invoke the helper methods from the JSP pages.

  1. Right-click the


    dvdrental

    source package node and select New > Java Class to open the New File wizard.

  2. Type FilmHelper for the class name.

  3. Confirm that dvdrental is selected as the Package. Click Finish.

  4. Adding the following code (in bold) to create a Hibernate session.


public class FilmHelper { *Session session = null; public FilmHelper() { this.session = HibernateUtil.getSessionFactory().getCurrentSession(); }* }

  1. Right-click in the editor and choose Fix Imports (Alt-Shift-I; ⌘-Shift-I on Mac) to add any required import statements (


    org.hibernate.Session

    ) and save your changes.

You will now modify

FilmHelper.java

to add methods that query the DB.

Enumerating Film Titles and Retrieving Actors Using an HQL Query

In this exercise you will create a Hibernate Query Language (HQL) query that queries the database to retrieve a list of film titles from the Film table. You will then add a method that queries both the Actor and Film_actor tables to fetch the actors involved in a particular film.

The Film table has 1000 records so the method to retrieve the list of films should be able to retrieve records based on the

filmId

primary key. You will use the HQL editor to construct and test the HQL query. After you have created the correct query you will add a method to the class that can generate the proper query.

  1. Right-click the project node in the Projects window and choose Clean and Build.

  2. Right-click


    hibernate.cfg.xml

    in the Projects window and choose Run HQL Query to open the HQL query editor.

  3. Select hibernate.cfg from the drop down list in the toolbar.

  4. Test the connection by typing the following in the editor and clicking the Run HQL Query button ( images:./run_hql_query_16.png[title=”Run HQL Query button”] ) in the toolbar.


from Film

When you click Run HQL Query you can see the results of the query in the bottom window of the HQL query editor.

If you click the SQL button you can see the equivalent SQL query.


select film0_.film_id as col_0_0_ from sakila.film film0_

  1. Type the following query to retrieve the records in the Film table where the film id is between 100 and 200.


from Film as film where film.filmId between 100 and 200

The result window displays a list of records. Now that you have tested that the query returns the desired results, you can use the query in the helper class.

  1. Add the following method


    getFilmTitles

    to

    FilmHelper.java

    to retrieve the films where the film id is between a certain range specified by the variables

    startID

    and

    endID

    .


public List getFilmTitles(int startID, int endID) { List

filmList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Film as film where film.filmId between '"+startID+"' and '"+endID+"'"); filmList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return filmList; }


  1. Add the following method


    getActorsByID

    that retrieves the actors in a particular film. The method constructs the query using

    filmId

    as the input variable.


public List getActorsByID(int filmId){ List

actorList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Actor as actor where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='" + filmId + "')"); actorList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return actorList; }


  1. Fix your imports and save your changes.

When you fix your imports you want to choose

java.util.List

and

org.hibernate.Query

.

Adding Additional Helper Methods

You will now add additional helper methods that create queries based on an input variable. You can check the queries in the HQL query editor.

  1. Add the following method to retrieve a list of categories according to


    filmId

    .


public Category getCategoryByID(int filmId){ List

categoryList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='" + filmId + "')"); categoryList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return categoryList.get(0); }


  1. Add the following method to retrieve a single film according to


    filmId

    .


public Film getFilmByID(int filmId){ Film film = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Film as film where film.filmId=" + filmId); film = (Film) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return film; }

  1. Add the following method to retrieve the film language according to


    langId

    .


public String getLangByID(int langId){ Language language = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Language as lang where lang.languageId=" + langId); language = (Language) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return language.getName(); }

  1. Save your changes.

#3. Hibernate Java Based Configuration with Maven + Eclipse + MySQL
#3. Hibernate Java Based Configuration with Maven + Eclipse + MySQL

Running the Project

The basics of the application are now complete. You can now run the application to check if everything is working correctly.

  1. Click Run Main Project in the main toolbar or right-click the DVDStore application node in the Projects window and choose Run.

The IDE saves all changed files, builds the application, and deploys the application to the server. The IDE opens a browser window to the URL

http://localhost:8080/DVDStore/

that displays the list of films.

  1. In your browser, click “View” to load


    browse.xhtml

    to view the film details.

Downloading the Solution Project

You can download the solution to this tutorial as a project in the following ways.

  • Download a zip archive of the finished project.

  • Checkout the project sources from the NetBeans Samples by performing the following steps:

    1. Choose Team > Subversion > Checkout from the main menu.

    2. In the Checkout dialog box, enter the following Repository URL:


      https://svn.netbeans.org/svn/samples~samples-source-code

      Click Next.

      1. Click Browse to open the Browse Repostiory Folders dialog box.

      2. Expand the root node and select samples/javaee/DVDStoreEE6. Click OK.

      3. Specify the Local Folder for the sources.

      4. Click Finish.

When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.

  1. Click Open Project in the dialog that appears when checkout is complete.

Notes. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

Troubleshooting

Most of the problems that occur with the tutorial application are due to communication difficulties between the GlassFish Server Open Source Edition and the MySQL database server. If your application does not display correctly, or if you are receiving a server error, you might want to look at the Troubleshooting section of the Creating a Simple Web Application Using a MySQL Database tutorial or the Connecting to a MySQL Database tutorial.

If you download and run the solution project you might see the following error in the Output window if it is the first time that you have deployed an application that uses the MySQL database.


SEVERE: JDBC Driver class not found: com.mysql.jdbc.Driver java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509) [...] at java.lang.Thread.run(Thread.java:680) SEVERE: Initial SessionFactory creation failed.org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver INFO: cleaning up connection pool: null INFO: Domain Pinged: stable.glassfish.org

In your browser window you might see a

java.lang.ExceptionInInitializerError

and the following stack trace.


java.lang.ExceptionInInitializerError at dvdrental.HibernateUtil.

(HibernateUtil.java:28) ... Caused by: org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver ... Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver ...

The output message states that the JDBC driver for the MySQL database was not found. The most probable reason is that you need to add the MySQL JDBC driver file to your GlassFish server installation. To confirm that the driver is missing, navigate to the

GLASSFISH-INSTALL/glassfish/domains/domain1/lib

directory on your local system (where GLASSFISH-INSTALL is your GlassFish installation directory). If the

domain1/lib

directory does not contain the JDBC driver file (for example,

mysql-connector-java-5.1.13-bin.jar

) you need to copy the JDBC driver to the directory. The MySQL JDBC driver is not added to your GlassFish installation when you install the server.

You can add a copy of the MySQL JDBC driver to your GlassFish installation by performing the following steps.

  1. Download the MySQL Connector/J JDBC driver.

  2. Extract the driver and copy the driver file (for example,


    mysql-connector-java-5.1.13-bin.jar

    ) to the

    domain1/lib

    directory of your GlassFish installation.

Alternatively, when you use the IDE to create an application that uses the MySQL database, the IDE can automatically copy the bundled MySQL JDBC driver to the GlassFish server when you deploy the project, if required. To confirm that the IDE will copy the necessary JDBC drivers, choose Tools > Servers from the main menu to open the Servers manager and confirm that the Enable JDBC Driver Deployment option is selected for your GlassFish server.

After you create and deploy a web application that uses the MySQL database, if you navigate to the

domain1/lib

directory of your local GlassFish installation you will see that directory contains the JDBC driver file.

In this article, we will learn how to configure Hibernate in our Java project with Maven. There are some problems when doing with Hibernate, and we will solve them to know more about configuration in Hibernate.

Let’s get started.

Configuring xml file for Hibernate

All information about configurations of Hibernate is contained in a standard Java properties file called

hibernate.properties

, or an XML file named

hibernate.cfg.xml

.

In this article, we will use the

hibernate.cfg.xml

file. It is located in

src/main/resouces

folder.

The content of

hibernate.cfg.xml

file like that:



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/java_sql true UTF-8 root 12345 thread update true true

In MySQL, we should note that when we remove two properties such as

hibernate.connection.useUnicode

, and

hibernate.connection.characterEncoding

. In Eclipse, we have an error like

Exception in thread main org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect

.

When we find DDL for

employee

table, we have:


CREATE TABLE `employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) )ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Therefore, in our table, it uses charset that is utf8mb4 – UTF8 Unicode. In order that hibernate can communicate with MySQL succesfully, we have to set value for

hibernate.connection.useUnicode

is

true

, and set value for

hibernate.connection.characterEncoding

is

UTF-8

.

To show the MySQL default character set, we have to login to the MySQL console and execute

SHOW VARIABLES LIKE 'char%';

.

If we want to change it, for example, to utf8, we have to add this:


default-character-set = utf8

to the client,

mysqld_safe

,

mysqld

and

mysqldump

section (may differ depending on configuration) in your my.cnf and restart the mysql daemon.

We can go to this link to refer some information about configuration in Hibernate.

When we want to connect with the other RDBMSs, we will have some values of

hibernate.dialect

,

hibernate.connection.driver_class

, and

hibernate.connection.url

.

  1. MySQL

    org.hibernate.dialect.MySQL57Dialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/database_name

  2. Oracle

    org.hibernate.dialect.Oracle12cDialect oracle.jdbc.OracleDriver jdbc:oracle:thin:@localhost:1521/database_name

  3. PostgreSQL

    org.hibernate.dialect.PostgreSQL95Dialect org.postgresql.Driver jdbc:postgresql://localhost:5432/database_name

  4. SQL Server

    org.hibernate.dialect.SQLServer2012Dialect com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc:sqlserver://localhost;instance=SQLEXPRESS;databaseName=java_sql

  5. MariaDB

    org.hibernate.dialect.MariaDB53Dialect org.mariadb.jdbc.Driver jdbc:mariadb://127.0.0.1:port_number/java_sql

Spring Boot Project for Beginners
Spring Boot Project for Beginners

Sử dụng Framework Hibernate trong Java Web Application

Framework trong phần mềm là một khái niệm dùng để chỉ những “cấu trúc dùng để hỗ trợ đã được định nghĩa sẵn” mà trong đó những dự án phần mềm khác có thể sử dung nó để phát triển. Một framework bao gồm những program hỗ trợ, core library và một ngôn ngữ lập trình để giúp phát triển và gắn những thành phần khác nhau ứng dụng phần mềm lại với nhau. Hibernate là một trong những ORM Framework. Hibernate framework là một framework cho persistence layer. Như vậy sử dụng Hibernate framework giúp bạn phát triển ứng dụng nhanh và chỉ còn chú tâm vào những layer khác mà không cần chú tâm nhiều đến persistence layer nữa. Hibernate giúp lưu trữ và truy vấn dữ liệu quan hệ mạnh mẽ và nhanh. Hibernate cho phép bạn truy vẫn dữ liệu bằng ngôn ngữ SQL mở rộng của Hibernate (HQL) hoặc bằng SQL thuần.Trong bài viết này tôi sẽ hướng dẫn các bạn làm quen với framework Hibernate qua những thao tác đơn giản. Hibernate cung cấp công cụ object relational mapping ORM như đã nói ở trên nên trong bài viết này tôi sẽ sử dụng luôn thế mạnh của framework này kết hợp cùng “JSF managed bean” và “JSF 2.x pages” để hiển lấy về dữ liệu và hiển thị ra giao diện web application.

Công cụ và môi trường phát triển

Trong bài viết này tôi sử dụng môi trường window 8.1 và cài đặt những IDE hỗ trợ sau:

  • Java SE Development Kit 8u71
  • Netbean IDE 8.1
  • XamPP 5.6.15 – For Mysql Version 5.x
  • GlassFish Server 4.1.1 – Nên chọn Netbean có sẵn server này (hoặc có thể dùng Jboss, Apache Tomcat…)

Các bạn có thể dùng các hệ quản trị cơ sử dữ liệu khác như Oracle DB, Sql Server … IDE để soạn thảo code thì có thể dùng những lựa chọn khác như eclip, IntelliJ IDEA … mỗi editor tool đều có sự khác biệt một chút nhưng đa phần đều support Hibernate.

Tạo mới một database

Trong bài viết này tối sẽ sử dụng luôn IDE netbean để tạo mới và thao tác với database. Để tạo một database các vào tab

Services

click chuột phải vào connection và chọn

Create Datatbase...

ở đây tôi lấy tên database là

liem_report_db

các bạn có thể thay đổi tùy theo ý thích

Bây giờ chúng ta sẽ tạo ra một table có với tên là

User

ở đây là table demo nên tôi chỉ tạo ít field, các bạn có thể tùy biến để phù hợp với yêu cầu công việc

như vậy là chúng ta đã có table User nhưng chưa có dữ liệu nên chúng ta sẽ thêm môt ít dữ liệu demo. Để thực hiện câu lệnh query luôn trên IDE thì chúng ta click chuột phải vào connect và chọn Execute Command…

Test dữ liệu vừa thêm vào


Select * from User;

Và chúng ta có kết quả:

Lưu ý: những bước ở trên mục đích là để tạo một database và thiết lập dữ liệu trong đó để sử dụng sau này, nếu bạn đã có database rồi thì không cần phải thực hiện loại. Tên database, tables, fields có thể tùy biến theo ý thích.

Tạo mới một project Web Application

Để tạo mới một project trong Netbean khá dễ bạn chỉ cần thao tác theo những bước sau:

Trên thanh Menu bạn chọn

File

>

New Project

(sử dung phím tắt Ctrl-Shift-N). Ở phần

Category

bạn chọn loại ứng dụng muốn tạo là

Web Application

sau đó click vào nút

Next

.

Ở bước này tôi sẽ yêu cầu chọn

Server

để

Run

project ở đây tôi chọn luôn server

Glass Server 4.1.1

đi kèm sẵn trong bản Netbean. Các bạn có thể chọn server khác.

Đến bước này khá quan trọng, các bạn chọn

JavaServer Faces



Hibernate 4.3.1

có thể version sẽ khác đi, tùy thuộc vào version của bản framework bạn bạn tích hợp vào Netbean

Sau đó click vào button

Finish

. Thế là chúng ta đã tạo ra một project được import các library của Hibernate và JSF (JavaServer Faces)

Hệ thống sẽ tự động sinh ra cho chúng ta một file có tên

hibernate.cfg.xml

nằm trong

Source Packages

>

giờ chúng ta sẽ thêm một số config cho nó như sau:

org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/liem_report_db root true thread org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

nếu các bạn để ý thì đây là những

property

cung cấp thông tin connection, việc này sẽ giúp cho Hibernate có thể thao tác với database của chúng ta.Thẻ cuối cùng hơi đặc biệt một chút

org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

ở đây chúng ta khai báo class sẽ xử lý genarate ra câu lệnh sql. Trong bản Hibernate 4 tôi sử dụng đường dẫn package như vây, nếu bạn sử dụng bản khác (thấp hơn) thì thay đổi đường dẫn tương ứng

Tạo mới một class HibernateUtil.java

Để tạo mới một Hibernate Util class chúng ta thao tác như sau:

– Chuột phải vào

Source Packages

chọn

New

>

Other

để mở cửa sổ

New File wizard

.- Chọn

Hibernate

từ list danh mục và ở khung đối diện

File Types

ta chọn

HibernateUtil.java

. Sau đó click vào button

Next

.Type HibernateUtil for the class name and dvdrental for the package. Click Finish.

Nhập vào tên cho class bạn muốn tạo. Ở đây tôi đặt tên là

HibernateUtil

cho dễ nhớ và chọn

Package



app

bạn có thể tùy biến tên class và package.

Tiếp theo chúng ta sẽ tạo một file

Hibernate Reverse Engineering

mục đích là để phục vụ cho việc mapping dữ liệu

Sau đó click vào button

Next

và chúng ta thấy hiện ra table có tên

user

như hình dưới:

Đây chính là tên table tôi tạo lúc đầu trong database, nếu các bạn tạo table khác thì tên nó sẽ hiện ra trong đó. Chúng ta chọn table và nhấn vào button

Add

move sang khung

Selected Table

sau đó chúng ta click button

Finish

Hibernate Mapping Files and POJOs

Bây giờ chúng ta sẽ sử dụng Hibernate Mapping Files and POJOs để generate file từ table

user

đã chọn ở trước đó. Chúng ta thực hiện như sau:

– Chuột phải vào

Source Packages

chọn

New

>

Other

để mở

New File wizard

.- Sau đó chúng ta chọn

Hibernate

ở khung bên cạnh chọn

Hibernate Mapping Files and POJOs from Database

sau đó click vào button

Next

.- Trong dropdown list chọn file cấu hình

hibernate.cfg.xml



hibernate.reveng.xml

– Check vào

JDK 5 Language Features

– Check vào

Domain Code



Hibernate XML Mappings

để hệ thống nhận biết định dạng cần thiết để generate code.- Đặt tên cho

Package name

tôi chọn là

app

. Sau đó click vào button

Finish

.

Ở công đoạn này nhiều người thường hay gặp phải message thông báo lỗi như hình dưới:

Nguyên nhân là do hệ thống không tìm được class

ClassicQueryTranslatorFactory

mà bạn đã cung cấp ở file cấu hình của Hibernate. Hãy kiểm tra lại version của hibernate và chỉnh sửa lại package cho đúng ở thuộc tính

org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

Lưu ý: để nhanh chóng check xem đường dẫn đã đúng hay chưa bạn chỉ cần tạo mới một Class và import đường dẫn đó vào, nếu không tồn tại IDE sẽ báo đỏ, còn không thì đường dẫn là hợp lệ

Sau đó ta click vào

Finish

. Hệ thống sẽ tự động sinh ra 2 file mới trong app package đó là

User.java



User.hbm.xml

Class User đã có sẵn các field và được mapping thành các property dễ dàng cho việc thao tác sau này.

User.hbm.xml

chứa thông tin mapping với user table:File: User.java


import java.util.Date; /** * User generated by hbm2java */ public class User implements java.io.Serializable { private int id; private String firstName; private String lastName; private String username; private String password; private Date created; public User() { } public User(int id, String username) { this.id = id; this.username = username; } public User(int id, String firstName, String lastName, String username, String password, Date created) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.username = username; this.password = password; this.created = created; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public Date getCreated() { return this.created; } public void setCreated(Date created) { this.created = created; } }

File: User.hbm.xml

Hibernate hỗ trợ thực thi HQL query để phục vụ cho việc truy xuất dữ liệu trong quá trình phát triển, bước này để test xem việc config, dữ liệu để connect tới db, mapping data đã thành công hay chưa:

Chuột phải vào file

hibernate.cfg.xml

chọn

Run HQL Query

để mở cửa sổ

HQL Query

sau đó ta thực hiện câu lệnh truy vấn


from User

Và được kết quả như trong ảnh, nếu không hiện ra hoặc báo

Generate erro

thì bạn kiểm tra lại file cấu hình của hibernate

Tạo mới class UserHelper.java

Chúng ta tạo chuột phải vào

app

package để create một class tên có thể tùy biến, ở đây tôi đặt là

UserHelper

cho dễ nhớ:


/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package app; /** * * @author DUYLIEMPRO */ public class UserHelper { public UserHelper() { } }

Sau đó viết thêm các method để lấy dữ liệu ra:


/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package app; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; /** * * @author DUYLIEMPRO */ public class UserHelper { Session session = null; List


userList; public UserHelper() { this.session = HibernateUtil.getSessionFactory().getCurrentSession(); } @SuppressWarnings(“unchecked”) public List


getUserList() { userList = new ArrayList


(); try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery(“from User as user”); userList = (List


) q.list(); } catch (Exception e) { userList = null; e.printStackTrace(); } return userList; } public User getUserByID(int userId) { User user = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery(“from User as user where user.id=” + userId); user = (User) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return user; } }

Tạo mới JSF Managed Bean

Bước này mục đích là tạo ra bean class để lấy dữ liệu fill ra file view.Để tạo một bean class các bạn thực hiện như sau:

– Chuột phải vào

source package

chọn

New

>

Other

.- Chọn

JSF Managed Bean

trong danh mục

JavaServer Faces

. Sau đó click

Next

.- Nhập tên bean class

UserController

.- Nhập tên package là

app

– Nhập

UserController

cho ô

name

sau này sẽ được sử dụng gọi ở file view (managed bean)- Thiết lập

Scope



Session

. Sau đó click vào

Finish

.

File: UserController.java


/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package app; import javax.inject.Named; import javax.enterprise.context.SessionScoped; import java.io.Serializable; /** * * @author DUYLIEMPRO */ @Named(value = "userController") @SessionScoped public class UserController implements Serializable { /** * Creates a new instance of UserController */ public UserController() { } }

Chúng ta sẽ viết các method xử lý lấy dữ liệu vào class này, ở đây tôi sẽ viết ví dụ 2 method, các bạn có thể thêm tùy ý:


/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package app; import javax.inject.Named; import javax.enterprise.context.SessionScoped; import java.io.Serializable; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; /** * * @author DUYLIEMPRO */ @Named(value = "userController") @SessionScoped public class UserController implements Serializable { DataModel useList; UserHelper helper; private User current; /** * Creates a new instance of UserController */ public UserController() { helper = new UserHelper(); } public User getSelected() { if (current == null) { current = new User(); } return current; } public DataModel getUseList() { if (useList == null) { useList = new ListDataModel(helper.getUserList()); } return useList; } }

Lưu ý

Muốn sử dụng được những function này trong file view (.xhtml) thì bắt buộc chúng ta phải viết tên method theo quy ước “get” + tên method(Tên method phải viết hoa chữ cái đầu). Khi hiển thị trên file view thì tiền tố “get” tự động sẽ bị remove, chữ cái đầu trong tên method sẽ tự động chuyển sang thường.

Tạo mới file Web Pages

Ở đây tôi sẽ sử dụng template để dễ dàng hơn cho việc thiết lập layout chung cho nhiều page, để tạo một template các bạn làm như sau:

– Chuột phải vào

source package

chọn

New

>

Other

.- Chọn

Facelets Template

trong danh mục

JavaServer Faces

. sau đó click

Next

.- Tôi đặt tên là

template

và chọn layout style sử dụng

CSS

(Table đều được).- Click vào button

Finish

.Kết quả là chúng ta được một file: template.xhtml trong thư mục web pages


Top


Content

Tùy layout bạn chọn mà sẽ có nội dung khác nhau nhưng tất cả đều thẻ


Content

Đây là nơi mà nội dung sẽ được chèn vào khi sử dụng template này.

Khi tạo mới ứng dụng hệ thống sẽ tự động tạo mới cho ta file

index.xhtml

trong thư mục

Web Pages

chúng ta sẽ sử dụng luôn file này để hiển thị dữ liệu. Tôi sẽ sử dụng JSF lib để sử dụng layout và hiển thị dữ liệu ra:

Lưu ý


xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:f="http://xmlns.jcp.org/jsf/core"

Đây là khai báo tên các thẻ sẽ được sẽ được sử dụng trong file view . Các bạn có thể thay đổi tên thẻ sẽ sử dụng vd: xmlns:a=”http://java.sun.com/jsf/html” và lúc dùng gọi

Run Project

Để chạy thử project các bạn chuột phải vào tên project chọn

Clean and Build

để hệ thống compile nếu có lỗi sẽ thông báo ở cửa sổ Output dưới. 2. Sau khi build xong chúng ta chuột phải vào projec một lần nữa chọn run (Lần đầu hệ thống sẽ start

GlassFish Server

nên hơi lâu một chút) nếu ok dưới cửa sổ sẽ thông báo


Incrementally deploying report Completed incremental distribution of report run-deploy: Browsing: http://localhost:8080/report run-display-browser: run: BUILD SUCCESSFUL (total time: 0 seconds)

và trình duyệt sẽ bật ra cửa sổ vối đường link: http://localhost:8080/report

Và chúng ta được kết quả như hình bên dưới:

Database file

Đây là file datbase export cho những bạn nào cần:


CREATE DATABASE `liem_report_db`; USE `liem_report_db`; CREATE TABLE `user` ( `id` int(11) NOT NULL, `first_name` varchar(50) DEFAULT NULL, `last_name` varchar(50) DEFAULT NULL, `username` varchar(20) NOT NULL, `password` varchar(32) DEFAULT NULL, `created` time DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `user` VALUES ('1', 'Tran', 'Liem', 'tranducliem', '25f9e794323b453885f5181f1b624d0b', '00:00:00'); INSERT INTO `user` VALUES ('2', 'Le', 'Minh', 'levanminh', '25f9e794323b453885f5181f1b624d0b', '00:00:00'); INSERT INTO `user` VALUES ('3', 'Phan', 'Tuan', 'phanquoctuan', '25f9e794323b453885f5181f1b624d0b', '00:00:00'); INSERT INTO `user` VALUES ('4', 'Tran', 'Sang', 'tranvansang', '25f9e794323b453885f5181f1b624d0b', '00:00:00');

BTV.Trần Thị Thu HuyềnPhòng Truyền Thông IMicroSoft Việt NamHotline: 0916 878 224Email: [email protected]

Bạn đang muốn tìm kiếm 1 công việc với mức thu nhập cao.✅ Hoặc là bạn đang muốn chuyển đổi công việc mà chưa biết theo học ngành nghề gì cho tốt.✅ Giới thiệu với bạn Chương trình đào tạo nhân sự dài hạn trong 12 tháng với những điều đặc biệt mà chỉ có tại IMIC và đây cũng chính là sự lựa chọn phù hợp nhất dành cho bạn:👉 Thứ nhất: Học viên được đào tạo bài bản kỹ năng, kiến thức chuyên môn lý thuyết, thực hành, thực chiến nhiều dự án và chia sẻ những kinh nghiệm thực tế từ Chuyên gia có nhiều năm kinh nghiệm dự án cũng như tâm huyết truyền nghề.👉 Thứ hai: Được ký hợp đồng cam kết chất lượng đào tạo cũng như mức lương sau tốt nghiệp và đi làm tại các đối tác tuyển dụng của IMIC. Trả lại học phí nếu không đúng những gì đã ký kết.👉 Thứ ba: Cam kết hỗ trợ giới thiệu công việc sang đối tác tuyển dụng trong vòng 10 năm liên tục.👉 Thứ tư: Được hỗ trợ tài chính với mức lãi suất 0 đồng qua ngân hàng VIB Bank.👉 Có 4 Chương trình đào tạo nhân sự dài hạn dành cho bạn lựa chọn theo học. Gồm có:1) Data Scientist full-stack2) Embedded System & IoT development full-stack3) Game development full-stack4) Web development full-stack✅ Cảm ơn bạn đã dành thời gian lắng nghe những chia sẻ của mình. Và tuyệt vời hơn nữa nếu IMIC được góp phần vào sự thành công của bạn.✅ Hãy liên hệ ngay với Phòng tư vấn tuyển sinh để được hỗ trợ về thủ tục nhập học.✅ Chúc bạn luôn có nhiều sức khỏe và thành công!

Compilation and Execution

Here are the steps to compile and run the above mentioned application. Make sure, you have set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.

  • Create hibernate.cfg.xml configuration file as explained in configuration chapter.

  • Create Employee.hbm.xml mapping file as shown above.

  • Create Employee.java source file as shown above and compile it.

  • Create ManageEmployee.java source file as shown above and compile it.

  • Execute ManageEmployee binary to run the program.

You would get the following result, and records would be created in the EMPLOYEE table.

$java ManageEmployee …….VARIOUS LOG MESSAGES WILL DISPLAY HERE…….. First Name: Zara Last Name: Ali Salary: 1000 First Name: Daisy Last Name: Das Salary: 5000 First Name: John Last Name: Paul Salary: 10000 First Name: Zara Last Name: Ali Salary: 5000 First Name: John Last Name: Paul Salary: 10000

If you check your EMPLOYEE table, it should have the following records −

mysql> select * from EMPLOYEE; +—-+————+———–+——–+ | id | first_name | last_name | salary | +—-+————+———–+——–+ | 29 | Zara | Ali | 5000 | | 31 | John | Paul | 10000 | +—-+————+———–+——–+ 2 rows in set (0.00 sec mysql>

Spring Boot Full Course - Learn Spring Boot In 4 Hours | Spring Boot Tutorial For Beginner | Edureka
Spring Boot Full Course – Learn Spring Boot In 4 Hours | Spring Boot Tutorial For Beginner | Edureka

Creating entity that is corresponding to a table in MySQL

We will generate entity that is mapped to data types of

employee

table in MySQL.


import lombok.Data; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "employee") @Data public class Employee implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") private int id; @Column(name = "FULL_NAME") private String name; @Column(name = "AGE") private int age; public Employee() { // nothing to do } public Employee(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public Employee(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Employee: " + this.id + ", " + this.name + ", " + this.age; } }

We have some rules for persistent class that we can apply to our own cases.


  • All Java classes that will be persisted need a default constructor.
  • All classes should contain an ID in order to allow easy identification of our objects within Hibernate and the database. This property maps to the primary key column of a database table.

  • All attributes that will be persisted should be declared private and have


    getXXX()

    and

    setXXX()

    methods defined in the JavaBean style.

  • A central feature of Hibernate, proxies, depends upon the peristent class being either non-final, or the implementation of an interface that declares all public methods.

  • All classes that do not extend or implement some specialized classes and interface required by the EJB framework.

Creating the Web Pages

In this exercise you will create two web pages for displaying the data. You will modify the

index.xhtml

generated by the IDE to add a table that displays the films in the database. You will then create

browse.xhtml

to display a film’s details when you click the “View” link in the table. You will also create a JSF template page that is used by

index.xhtml

and

browse.xhtml

.

For more about using JSF 2.0 and Facelets templates, see Introduction to JavaServer Faces 2.0

Creating template.xhtml

You will first create the JSF Facelets template

template.xhtml

that is used in the composition of the

index.xhtml

and

browse.xhtml

pages.

  1. Right-click the DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template in the JavaServer Faces category. Click Next.

  3. Type template for the File Name and choose the first CSS layout style.

  4. Click Finish.

When you click Finish, the file

template.xhtml

opens in the editor. The template contains the following default code.



Top

Content


  1. Modify the

    element to change the default generated name to “body”.


Content

  1. Save your changes.

The content enclosed within the element in

index.xhtml

and

browse.xhtml

will be inserted into the location identified with


Content


in the template.

Modifying index.xhtml

When you created the web application, the IDE automatically generated the page

index.xhtml

. In this exercise you modify the page to display a list of film titles. The JSF page calls the methods in the JSF Managed Bean FilmController to retrieve the list of films and then displays a table with the film titles and descriptions.

  1. Expand the Web Pages folder in the Projects window and open


    index.xhtml

    in the editor.

The New Project wizard generated the following default

index.xhtml

page.




<br /> Facelet Title<br />


Hello from Facelets


  1. Modify the page to use the JSF

    andelements and add aelement.

When you start typing the tags, the IDE adds

xmlns:ui="http://java.sun.com/jsf/facelets"

tag library declaration.

The and elements are used in combination with the page template that you will create. The element references the location of the template that will be used by this page. The element references the position in the template that the enclosed code will occupy.

  1. Add the following navigation links that call the


    previous

    and

    next

    methods in the JSF managed bean.




* *


  1. Add the following


    dataTable

    element (in bold) to generate the table to display the retrieved items.



* *

  1. Save your changes.

The index page will now display a list of film titles in the database. Each row in the table includes a “View” link that invokes the

prepareView

method in the managed bean. The

prepareView

method returns “browse” and will open

browse.xhtml

.

Note. When you type the tag, the IDE will add

xmlns:f="http://java.sun.com/jsf/core

tag library declaration. Confirm that the tag library is declared in the file.

Creating browse.xhtml

You will now create the

browse.xhtml

page for displaying details of the selected film. You can use the Facelets Template Client wizard to create the page based on the JSF Facelets template

template.xhtml

that you created.

  1. Right-click DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template Client in the JavaServer Faces category. Click Next.

  1. Type browse for the File Name.

  2. Locate the Template for the page by clicking Browse to open the Browse Files dialog box.

  3. Expand the Web Pages folder and select


    template.xhtml

    . Click Select File.

  1. Select

    for the Generated Root Tag. Click Finish.

When you click Finish, the file

browse.xhtml

opens in the editor with the following code.




top


body


You can see that the new file specifies the

template.xhtml

file and that the tag has the property

name="body"

  1. Add the following code (in bold) between the

    tags to create the form and call the methods in the managed bean FilmController to retrieve the data and populate the form.




top


* *


You can see that

browse.xhtml

and

index.xhtml

will use the same page template.

  1. Save your changes.

Hibernate [creating dynamic web project and hibernate configuration files] - part 2
Hibernate [creating dynamic web project and hibernate configuration files] – part 2

Creating the Web Application Project

In this exercise you will create a web application project and add the Hibernate libraries to the project. When you create the project, you will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

  1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select Web Application from the Java Web category and click Next.

  2. Type DVDStore for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. Click Next.

For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

  1. Set the server to the GlassFish Server and set the Java EE Version to Java EE 6 Web or Java EE 7 Web. Click Next.

  2. Select the JavaServer Faces checkbox and use the default JSF 2.x libraries.

  3. Select the Hibernate checkbox in the list of frameworks.

  4. Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, you need to create the database connection.

When you click Finish, the IDE creates the web application project and opens the

hibernate.cfg.xml

file and

index.xhtml

in the editor.

If you expand the Libraries node in the Projects window, you can see that the IDE added the Hibernate libraries to the project.

Running the Project

The basics of the application are now complete. You can now run the application to check if everything is working correctly.

  1. Click Run Main Project in the main toolbar or right-click the DVDStore application node in the Projects window and choose Run.

The IDE saves all changed files, builds the application, and deploys the application to the server. The IDE opens a browser window to the URL

http://localhost:8080/DVDStore/

that displays the list of films.

  1. In your browser, click “View” to load


    browse.xhtml

    to view the film details.

Downloading the Solution Project

You can download the solution to this tutorial as a project in the following ways.

  • Download a zip archive of the finished project.

  • Checkout the project sources from the NetBeans Samples by performing the following steps:

    1. Choose Team > Subversion > Checkout from the main menu.

    2. In the Checkout dialog box, enter the following Repository URL:


      https://svn.netbeans.org/svn/samples~samples-source-code

      Click Next.

      1. Click Browse to open the Browse Repostiory Folders dialog box.

      2. Expand the root node and select samples/javaee/DVDStoreEE6. Click OK.

      3. Specify the Local Folder for the sources.

      4. Click Finish.

When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.

  1. Click Open Project in the dialog that appears when checkout is complete.

Notes. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

Troubleshooting

Most of the problems that occur with the tutorial application are due to communication difficulties between the GlassFish Server Open Source Edition and the MySQL database server. If your application does not display correctly, or if you are receiving a server error, you might want to look at the Troubleshooting section of the Creating a Simple Web Application Using a MySQL Database tutorial or the Connecting to a MySQL Database tutorial.

If you download and run the solution project you might see the following error in the Output window if it is the first time that you have deployed an application that uses the MySQL database.


SEVERE: JDBC Driver class not found: com.mysql.jdbc.Driver java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509) [...] at java.lang.Thread.run(Thread.java:680) SEVERE: Initial SessionFactory creation failed.org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver INFO: cleaning up connection pool: null INFO: Domain Pinged: stable.glassfish.org

In your browser window you might see a

java.lang.ExceptionInInitializerError

and the following stack trace.


java.lang.ExceptionInInitializerError at dvdrental.HibernateUtil.

(HibernateUtil.java:28) ... Caused by: org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver ... Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver ...

The output message states that the JDBC driver for the MySQL database was not found. The most probable reason is that you need to add the MySQL JDBC driver file to your GlassFish server installation. To confirm that the driver is missing, navigate to the

GLASSFISH-INSTALL/glassfish/domains/domain1/lib

directory on your local system (where GLASSFISH-INSTALL is your GlassFish installation directory). If the

domain1/lib

directory does not contain the JDBC driver file (for example,

mysql-connector-java-5.1.13-bin.jar

) you need to copy the JDBC driver to the directory. The MySQL JDBC driver is not added to your GlassFish installation when you install the server.

You can add a copy of the MySQL JDBC driver to your GlassFish installation by performing the following steps.

  1. Download the MySQL Connector/J JDBC driver.

  2. Extract the driver and copy the driver file (for example,


    mysql-connector-java-5.1.13-bin.jar

    ) to the

    domain1/lib

    directory of your GlassFish installation.

Alternatively, when you use the IDE to create an application that uses the MySQL database, the IDE can automatically copy the bundled MySQL JDBC driver to the GlassFish server when you deploy the project, if required. To confirm that the IDE will copy the necessary JDBC drivers, choose Tools > Servers from the main menu to open the Servers manager and confirm that the Enable JDBC Driver Deployment option is selected for your GlassFish server.

After you create and deploy a web application that uses the MySQL database, if you navigate to the

domain1/lib

directory of your local GlassFish installation you will see that directory contains the JDBC driver file.

Using Hibernate in a Web Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Web Application Project
  • Modifying the Hibernate Configuration File
  • Creating the

    HibernateUtil.java

    Helper File
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the

    FilmHelper.java

    Helper Class
  • Creating the JSF Managed Bean
  • Creating the Web Pages
  • Running the Project
  • See Also

In this tutorial, you use the NetBeans IDE to create and deploy a web application that displays data from a database. The web application uses the Hibernate framework as the persistence layer for retrieving and storing plain old Java objects (POJOs) to a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates how to add support for the Hibernate framework to the IDE and create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a JSF managed bean and JSF 2.0 pages to display the data.

Before starting this tutorial you may want to familiarize yourself with the following documents.

  • Hibernate documentation at hibernate.org

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.1, 7.2, 7.3, 7.4, Java EE version

Version 6 or 7

GlassFish Server Open Source Edition

3.x or 4.x

Version 5.x

Sakila Database

Plugin available from update center

You can download a zip archive of the finished project.

Spring Boot Hibernate Web Application - Creating a project and Testing the application [Part 1]
Spring Boot Hibernate Web Application – Creating a project and Testing the application [Part 1]

22.2 Create a Web Application Project

In this section we will discuss how to create a web application using eclipse. We can create it manually as well

  1. To create a new project go to

File -> New -> Project -> Web -> Dynamic Web Project ->Next (refer below)

Once you click Next, new window will open (refer below)

  • Project Name –Give it a name. This will be the name of your web application. In the above figure, web application with name “ManageDatabase” will be created
  • “Target Runtime”, choose “Apache Tomcat v7.0”
  • Leave rest all as default values .Click Finish

Once done , a new project with name “ManageDatabase” will be created (refer below figure)

Details-

  1. All Java code will be created under src folder
  2. All static contents and jsp will be created under WebContent

To create a War file, Right Click on Project -> Export -> War file

Clicking on War file, a new window will be opened (refer below). Choose a Destination as the webapps folder of your tomcat installation directory.

Note- You can select any destination folder and eclipse will create a ManageDatabase.war file at the selected location. However, each server has its own directory from where it deploys the war file.

In case of tomcat “webapps” directory is the deployment directory and for any web application to be deployed on tomcat, it has to be placed in webapps.

22.2.2 Add Hibernate Jar files in build path.

Now is the time to add the jar files of Hibernate that we downloaded in Chapter 3 (section 3.6) in the java project.

Copy the below jar files and paste in WebContent\WEB-INF\lib folder

  1. antlr-2.7.7.jar
  2. dom4j-1.6.1.jar
  3. hibernate-commons-annotations-4.0.5.Final.jar
  4. hibernate-core-4.3.7.Final.jar
  5. hibernate-jpa-2.1-api-1.0.0.Final.jar
  6. jandex-1.1.0.Final.jar
  7. javassist-3.18.1-GA.jar
  8. jboss-logging-3.1.3.GA.jar
  9. jboss-logging-annotations-1.2.0.Beta1.jar
  10. jboss-transaction-api_1.2_spec-1.0.0.Final.jar
  11. mysql-connector-java-5.1.18-bin.jar

Creating the HibernateUtil.java Helper File

To use Hibernate you need to create a helper class that handles startup and that accesses Hibernate’s

SessionFactory

to obtain a Session object. The class calls

configure()

and loads the

hibernate.cfg.xml

configuration file and then builds the

SessionFactory

to obtain the Session object.

In this section you use the New File wizard to create the helper class

HibernateUtil.java

.

  1. Right-click the Source Packages node and select New > Other to open the New File wizard.

  2. Select Hibernate from the Categories list and HibernateUtil.java from the File Types list. Click Next.

  3. Type HibernateUtil for the class name and dvdrental for the package. Click Finish.

When you click Finish,

HibernateUtil.java

opens in the editor. You can close the file because you do not need to edit the file.

Spring Boot CRUD Tutorial with IntelliJ IDEA, MySQL, JPA, Hibernate, Thymeleaf and Bootstrap
Spring Boot CRUD Tutorial with IntelliJ IDEA, MySQL, JPA, Hibernate, Thymeleaf and Bootstrap

Create POJO Classes

The first step in creating an application is to build the Java POJO class or classes, depending on the application that will be persisted to the database. Let us consider our Employee class with getXXX and setXXX methods to make it JavaBeans compliant class.

A POJO (Plain Old Java Object) is a Java object that doesn’t extend or implement some specialized classes and interfaces respectively required by the EJB framework. All normal Java objects are POJO.

When you design a class to be persisted by Hibernate, it is important to provide JavaBeans compliant code as well as one attribute, which would work as index like id attribute in the Employee class.

public class Employee { private int id; private String firstName; private String lastName; private int salary; public Employee() {} public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary; } public int getId() { return id; } public void setId( int id ) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName( String first_name ) { this.firstName = first_name; } public String getLastName() { return lastName; } public void setLastName( String last_name ) { this.lastName = last_name; } public int getSalary() { return salary; } public void setSalary( int salary ) { this.salary = salary; } }

Creating the Web Application Project

In this exercise you will create a web application project and add the Hibernate libraries to the project. When you create the project, you will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

  1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select Web Application from the Java Web category and click Next.

  2. Type DVDStore for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. Click Next.

For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

  1. Set the server to the GlassFish Server and set the Java EE Version to Java EE 6 Web or Java EE 7 Web. Click Next.

  2. Select the JavaServer Faces checkbox and use the default JSF 2.x libraries.

  3. Select the Hibernate checkbox in the list of frameworks.

  4. Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, you need to create the database connection.

When you click Finish, the IDE creates the web application project and opens the

hibernate.cfg.xml

file and

index.xhtml

in the editor.

If you expand the Libraries node in the Projects window, you can see that the IDE added the Hibernate libraries to the project.

JAVA Hibernate CRUD Create Read Update Delete Project
JAVA Hibernate CRUD Create Read Update Delete Project

Add dependencies of Maven to pom.xml file





org.hibernate


hibernate-core


4.3.6.Final




mysql


mysql-connector-java


5.1.6




org.javassist


javassist


3.18.0-GA




org.projectlombok


lombok


1.18.6


provided



Web Application With Hibernate,JSP and Servlet using Eclipse

Hibernate integration with Servlet and JSP :

In this tutorial, we are going to create a web application with hibernate. We are going to insert the record of the user in the database.We will create Registration form for getting user data.These data we will collect in servlet and finally insert these data into Database by using hibernate.

For creating the web application, we are using JSP for presentation logic, Servlet class for controller layer and DAO class for database access codes.

Tools and Technologies :

  • JDK
  • Hibernate 3.6.3.Final
  • Eclipse
  • MySQL 5.5.
  • Tomcat

Follow the steps mentioned below to create this example.

Step 1 : Create Dynamic Web Project :

Open eclipse IDE,and go to

File -> New -> Project ->

and select

Dynamic Web Project

,specify the project name as HibernateWebApp and click on next -> finish .

Step 2 : Add Jar files for hibernate and mysql :

Copy all the jar files as shown below inside lib folder of the project

Step 3 : Creating web pages :

Now let us create register.jsp file inside Web-Content folder of your project.This is a simple form where user can provide his/her detail.

Right Click on Web-Content then New -> JSP File and provide the name of JSP file as register.jsp and click Finish.

Add following code in this file

register.jsp

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>













Registration Form


	

Registration Form

User Name :
Password :
Confirm Password :
email :
Phone :
City :

Step 4 : Creating Java Classes :

Create a package com.jwt.hibernate.controller and create a java class UserControllerServlet in this package and add following code in this class.

UserControllerServlet.java

package com.jwt.hibernate.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jwt.hibernate.dao.UserDAO;

public class UserControllerServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userName");
		String password = request.getParameter("password1");
		String email = request.getParameter("email");
		String phone = request.getParameter("phone");
		String city = request.getParameter("city");

		HttpSession session = request.getSession(true);
		try {
			UserDAO userDAO = new UserDAO();
			userDAO.addUserDetails(userName, password, email, phone, city);
			response.sendRedirect("Success");
		} catch (Exception e) {

			e.printStackTrace();
		}

	}
}

Above class is controller class for our application.In this class we are collecting the data from user and storing the data by calling UserDAO class addUserDetails method.If the database insertion is successful request will be forwarded to Success.java Servlet class.

User.java

This is a simple bean class representing the Persistent class in hibernate.

Create a package com.jwt.hibernate.bean,in this package create java class User.java and add following code in this class.


package com.jwt.hibernate.bean;

public class User {
	private int id;
	private String userName;
	private String password1;
	private String email;
	private String phone;
	private String city;

	public int getId() {
		return id;
	}

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

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword1() {
		return password1;
	}

	public void setPassword1(String password1) {
		this.password1 = password1;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

}
UserDAO.java

This is DAO class. In this class we have implemented addUserDetails() method where we are adding the user details to database by using hibernate.

Create a package com.jwt.hibernate.dao,in this package create java class UserDAO.java and add following code in this class.


package com.jwt.hibernate.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.jwt.hibernate.bean.User;

public class UserDAO {

	public void addUserDetails(String userName, String password, String email,
			String phone, String city) {
		try {
			// 1. configuring hibernate
			Configuration configuration = new Configuration().configure();

			// 2. create sessionfactory
			SessionFactory sessionFactory = configuration.buildSessionFactory();

			// 3. Get Session object
			Session session = sessionFactory.openSession();

			// 4. Starting Transaction
			Transaction transaction = session.beginTransaction();
			User user = new User();
			user.setUserName(userName);
			user.setPassword1(password);
			user.setEmail(email);
			user.setCity(city);
			user.setPhone(phone);
			session.save(user);
			transaction.commit();
			System.out.println("\n\n Details Added \n");

		} catch (HibernateException e) {
			System.out.println(e.getMessage());
			System.out.println("error");
		}

	}

}
Success.java

User will be redirected to this class after successful insertion of data.


package com.jwt.hibernate.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Success extends HttpServlet {

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter writer = response.getWriter();

		writer.println("" + "" + ""
				+ "Details Added Successfully" + "" + ""
				+ "");
	}

}

Step 5 : Create the mapping file :

Mapping file maps the User class with the table of the database.

Right click on com.jwt.hibernate.bean then navigate to

New -> Other -> General -> Next

and provide the name of file as

user.hbm.xml

and click on finish.After creating user.hbm.xml add following code in this file.

user.hbm.xml

Step 6 : Create the Configuration file :

The configuration file contains informations about the database and mapping file. Conventionally, its name should be hibernate.cfg.xml .Configuration file must be in classpath of your Project.Place this file in src of your project by default it will added to classpath of your project.

hibernate.cfg.xml













	
		com.mysql.jdbc.Driver
		jdbc:mysql://localhost:3306/jwt
		root
		mukesh
		org.hibernate.dialect.MySQLDialect
		true
		true
		create 
		
	

Step 7: Create web.xml file :

Create web.xml file inside WEB-INF directory of project.

web.xml



	HibernateWebApp
	
		User
		User
		com.jwt.hibernate.controller.UserControllerServlet
	
	
		Success
		Success
		com.jwt.hibernate.controller.Success
	
	
		User
		/register
	
	
		Success
		/Success
	
	
		register.jsp
	

Directory structure of the project :

Directory Structure of the project is given bellow.

Run the Application :

To run the hibernate web application, right click on the project then Run as -> Run On Server select Tomcat -> Next ->Finish.

Output in Browser :

Fill the form and click on submit button :

If everything is fine and data is inserted into table user will be redirected to Success page as shown below :

Check the data in the Database :

After submitting the data USER table is created by Hibernate and data is inserted into this table as shown above :

You can download the source code of the example by clicking on the Download link below.


Download


Previous


Next Article

Web Application With Hibernate,JSP and Servlet using Eclipse

Project-2 Register & Login Page using Spring MVC , Hibernate, JSP | Spring MVC Project
Project-2 Register & Login Page using Spring MVC , Hibernate, JSP | Spring MVC Project

Keywords searched by users: hibernate web application example

Using Hibernate In A Web Application
Using Hibernate In A Web Application
Hibernate Example Tutorial
Hibernate Example Tutorial
Spring Boot Crud Web Application With Thymeleaf, Spring Mvc, Spring Data  Jpa, Hibernate, Mysql - Youtube
Spring Boot Crud Web Application With Thymeleaf, Spring Mvc, Spring Data Jpa, Hibernate, Mysql – Youtube
Tutorial:Create Struts2 Hibernate Example Application In Eclipse
Tutorial:Create Struts2 Hibernate Example Application In Eclipse
Hibernate Tutorial For Beginners | Digitalocean
Hibernate Tutorial For Beginners | Digitalocean
Hibernate Architecture Tutorial- Javatpoint
Hibernate Architecture Tutorial- Javatpoint
Ví Dụ Login Trong Spring 4 Web Mvc - Hibernate 4 Annotation - Viettuts
Ví Dụ Login Trong Spring 4 Web Mvc – Hibernate 4 Annotation – Viettuts
Login Application Using Jsp + Servlet + Hibernate + Mysql Example | Java  Guides - Youtube
Login Application Using Jsp + Servlet + Hibernate + Mysql Example | Java Guides – Youtube
Spring Boot, Mysql, Jpa, Hibernate Restful Crud Api Tutorial | Callicoder
Spring Boot, Mysql, Jpa, Hibernate Restful Crud Api Tutorial | Callicoder
Spring Mvc Hibernate Mysql Integration Crud Example Tutorial | Digitalocean
Spring Mvc Hibernate Mysql Integration Crud Example Tutorial | Digitalocean
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Giới Thiệu Về Hibernate - Gp Coder (Lập Trình Java)
Giới Thiệu Về Hibernate – Gp Coder (Lập Trình Java)
Spring Boot, Mysql, Jpa, Hibernate Restful Crud Api Tutorial | Callicoder
Spring Boot, Mysql, Jpa, Hibernate Restful Crud Api Tutorial | Callicoder
Ví Dụ Login Trong Spring 4 Web Mvc – Hibernate 4 Xml Mapping - Viettuts
Ví Dụ Login Trong Spring 4 Web Mvc – Hibernate 4 Xml Mapping – Viettuts
Tutorial:Create Spring 3 Mvc Hibernate 3 Example Using Maven In Eclipse
Tutorial:Create Spring 3 Mvc Hibernate 3 Example Using Maven In Eclipse
Example: Using Java + Springboot + Hibernate And Iris Database To Create
Example: Using Java + Springboot + Hibernate And Iris Database To Create
Spring Boot Hibernate Mysql Crud Rest Api Tutorial | Controller, Service  And Dao Layer | Full Course - Youtube
Spring Boot Hibernate Mysql Crud Rest Api Tutorial | Controller, Service And Dao Layer | Full Course – Youtube
Hibernate Right Join Example | Hibernate Right Join | Hibernate Join Online  Tutorialspoint
Hibernate Right Join Example | Hibernate Right Join | Hibernate Join Online Tutorialspoint
How To Create A Mvc Web Application Using Struts Hibernate And Velocity –  Giuseppe Urso Blog
How To Create A Mvc Web Application Using Struts Hibernate And Velocity – Giuseppe Urso Blog
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Kieu Trong Khanh: Hibernate 3.2.5 In Mvc Web Application With Netbean 6.9.1  And Mysql Server
Kieu Trong Khanh: Hibernate 3.2.5 In Mvc Web Application With Netbean 6.9.1 And Mysql Server
Learn Hibernate Tutorial - Javatpoint
Learn Hibernate Tutorial – Javatpoint
Spring Mvc And Hibernate Web Application One-To-One Mapping Database Example  [Xml Configuration] - B2 Tech
Spring Mvc And Hibernate Web Application One-To-One Mapping Database Example [Xml Configuration] – B2 Tech
Jpa / Hibernate One To Many Mapping Example With Spring Boot | Callicoder
Jpa / Hibernate One To Many Mapping Example With Spring Boot | Callicoder
Struts 2 And Hibernate Integration Example- Xml Based - Websparrow
Struts 2 And Hibernate Integration Example- Xml Based – Websparrow

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *