Jakarta Faces 4 (JSF) with JDBC as Backend DataAccess Example
This example demonstrates the usage of the j-framework in creating a project that uses relational database engine as persistence layer, and uses JDBC.
Prerequisites:
-
You should have JDK 17+ Installed. (Click Here).
-
You should create a Maven Project.
-
You should enable snapshot versions. (Click Here).
Project Content:
This section contains what you should add to your code structure for this example.
-
Maven Project with pom.xml that has the following contents:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.jalalkiswani</groupId>
<artifactId>j-app-webstack</artifactId>
<version>7.0.0-SNAPSHOT</version>
</parent>
<artifactId>j-framework-webstack-jdbc-example</artifactId>
<packaging>war</packaging>
</project>
-
Database configurations file located at
src/main/resources/config.properties
that has the following content:
hibernate.connection.driver_class = org.h2.Driver
hibernate.connection.url = jdbc:h2:file:./h2db.data
hibernate.dialect = org.hibernate.dialect.H2Dialect
#MySql config
#hibernate.connection.driver_class = com.mysql.jdbc.Driver
#hibernate.connection.url = jdbc:mysql://localhost:3306/app?useSSL=false
#hibernate.dialect = org.hibernate.dialect.MySQL57Dialect
#Oracle Config, you will need to add oracle driver dependncy,
#checkout, option 4(System Path): https://www.mkyong.com/maven/how-to-add-oracle-jdbc-driver-in-your-maven-local-repository/
#hibernate.connection.driver_class = oracle.jdbc.driver.OracleDriver
#hibernate.connection.url = jdbc:oracle:thin:@localhost:1521/orclpdb1
#hibernate.dialect = org.hibernate.dialect.Oracle12cDialect
#hibernate.c3p0.preferredTestQuery=SELECT 1 FROM DUAL
hibernate.connection.username = sa
hibernate.connection.password = sa
hibernate.c3p0.min_size=1
hibernate.c3p0.max_size=4
hibernate.c3p0.timeout=3
hibernate.c3p0.max_statements=50
hibernate.hbm2ddl.auto=update
db-entities-packages=com.app
-
SQL script located at
src/main/resources/script.sql
that has the following content:
create table person(
id integer generated by default as identity,
national_id varchar(250),
name varchar(250),
email varchar(250),
address varchar(250)
);
-
Java Model class is located at
src/main/java/com/app/person/Model.java
that has the following content:
package com.app.person;
import java.io.Serializable;
public class Model implements Serializable {
private Integer id;
private String nationalId;
private String name;
private String email;
private String address;
public void setId(Integer id){
this.id=id;
}
public Integer getId(){
return this.id;
}
public void setNationalId(String nationalId){
this.nationalId=nationalId;
}
public String getNationalId(){
return this.nationalId;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
public void setEmail(String email){
this.email=email;
}
public String getEmail(){
return this.email;
}
public void setAddress(String address){
this.address=address;
}
public String getAddress(){
return this.address;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
return this.getId().equals(((Model) obj).getId());
}
@Override
public int hashCode() {
if(this.id==null) {
return toString().hashCode();
}
return this.id.hashCode();
}
@Override
public String toString(){
StringBuffer buf=new StringBuffer();
buf.append(this.id).append(",");
buf.append(this.nationalId).append(",");
buf.append(this.name).append(",");
buf.append(this.email).append(",");
buf.append(this.address).append(",");
return buf.toString();
}
}
-
Faces Controller located at
src/main/java/com/app/person/Controller.java
which contains the following:
package com.app.person;
import java.util.List;
import java.util.Vector;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;
import com.jk.web.faces.controllers.JKWebController;
@Named("controller")
@ViewScoped
public class Controller extends JKWebController {
DataAccess da = new DataAccess();
Model model;
List<Model> modelList;
List<Model> filterList;
public boolean isAllowAdd() {
return getModel().getId() == null;
}
public String add() {
da.add(model);
refresh();
success("Added Successfully");
return null;
}
public boolean isAllowUpdate() {
return getModel().getId() != null;
}
public String update() {
da.update(model);
int id = getModel().getId();
success("Updated Successfully");
refresh();
// to ensure getting updated version from DB
this.model = da.find(id);
return null;
}
public boolean isAllowDelete() {
return getModel().getId() != null;
}
public String delete() {
da.delete(getModel().getId());
success("Deleted Successfully");
refresh();
return null;
}
public String reset() {
setModel(null);
return null;
}
public Model getModel() {
if (model == null) {
model = new Model();
}
return model;
}
public void setModel(Model model) {
this.model = model;
}
public List<Model> getModelList() {
if (modelList == null) {
modelList = da.getAll();
}
return modelList;
}
public List<Model> getFilterList() {
return filterList;
}
public void setFilterList(Vector<Model> filterList) {
this.filterList = filterList;
}
protected void refresh() {
this.modelList = null;
setModel(null);
}
}
-
Data Access class located at
src/main/java/com/app/person/DataAccess.java
which contains teh following:
package com.app.person;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.jk.data.dataaccess.JKDataAccessFactory;
import com.jk.data.dataaccess.core.JKDataAccessService;
public class DataAccess {
JKDataAccessService service = JKDataAccessFactory.getDataAccessService();
public void add(Model person) {
String sql = "INSERT INTO person (national_id,name,email,address) VALUES (?,?,?,?)";
service.execute(sql, person.getNationalId(), person.getName(), person.getEmail(), person.getAddress());
}
public Model find(int id) {
return service.find("SELECT * FROM person WHERE id=?", this::populatePerson, id);
}
public boolean delete(int id) {
return service.execute("DELETE FROM person WHERE id=?", id) == 1;
}
public boolean update(Model person) {
String sql = "UPDATE person SET national_id=?,name=?,email=?,address=? WHERE id=?";
int records = service.execute(sql, person.getNationalId(), person.getName(), person.getEmail(),
person.getAddress(), person.getId());
return records == 1;
}
public List<Model> getAll() {
return service.getList("SELECT * FROM person", this::populatePerson);
}
protected Model populatePerson(ResultSet rs) throws SQLException {
Model person = new Model();
person.setId((Integer) rs.getObject("id"));
person.setNationalId((String) rs.getObject("national_id"));
person.setName((String) rs.getObject("name"));
person.setEmail((String) rs.getObject("email"));
person.setAddress((String) rs.getObject("address"));
return person;
}
}
-
Faces View located at
src/main/webapp/index.xhtml
which contains the following:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.org/ui" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core" xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:composition template="/WEB-INF/templates/default.xhtml">
<ui:define name="page-title">Home Page</ui:define>
<ui:define name="contents">
<div class="product-banner">
<div class="product-name">Welcome to j-framework Demo</div>
<div class="product-summary">Your product summary</div>
<div class="product-version">Version 1.0</div>
</div>
</ui:define>
</ui:composition>
</html>
-
Main java class located at
src/main/java/com/app/App.java
which contains the following:
package com.app;
import com.jk.data.dataaccess.JKDataAccessFactory;
import com.jk.data.dataaccess.core.JKDataAccessService;
import com.jk.web.embedded.JKWebApplication;
public class App {
public static void main(String[] args) {
JKDataAccessService da = JKDataAccessFactory.getDataAccessService();
if (!da.isTableExists("PERSON")) {
da.runScript("/script.sql");
}
JKWebApplication.run(8080);
}
}
Alternatively, you can clone or download the tutorial repository then import the project into your IDE. |
How to run Project:
-
Set up the project with the content shown above.
-
Inside your IDE, go to the
src/main/java/com/app/App.java
class.
-
Next, run it as a Java Application.
-
Your program will start running and will open your browser to show you the result of the run. Alternatively, after running the code, you can open any browser to localhost on port 8080, and it will show you the run output as well.
Example Explanation
-
The first page you would see when you run the code is the home page, from it, you can see the link to the Person page.
-
After heading to the Person page, you will see a form which will enter the data you input in it into the database. After filling in the form, press the Add button to add it to the database.
-
You can see the new entry in the person data table shown below the form.
-
Pressing the Reset button will clear the data inside the form fields.