JSF Database Example - MySQL JDBC

Welcome to JSF Database example. We will use JSF with MySQL database and use JDBC for our example. Java Server Faces can be connected to database to perform operations on the data using JDBC API.

JSF Database Example

Lets consider an example of pulling the data from a Car table residing in the database and display them using JDBC.

First, create the car table in mysql database as shown below.

Create a new database cardb as

Use the created database cardb to create table as

Create the table car as shown below

Now we shall insert some values into the Car table as

Model Classes

Now Create the plain old java object class Car.java with the fields and getter and setter methods as shown below.

Create a managed bean CarBean.java using which we will establish a connection to the database via Class.forName method to execute a query to pull the data from the car table. Note that this is very inefficient way to create and manage database connections. You should use JNDI Connection with Datasource or create a utility class for this. However for simplicity, I am not having those extra classes in my project.

Now create JSF view page car.xhtml as shown below.

Note that we need to include MySQL Connector jar in our project for getting MySQL database connection. So add below dependency in pom.xml file. Add mysql connector jar version according to your MySQL installation.

Now run the application and you will see below output response page.


Finally below image shows the project structure in Eclipse.


You can download the project from below link and play around with it to learn more.

By admin

Leave a Reply

%d bloggers like this: