Archive for the ‘JDBC’ category

Dynamic JSF application with MySQL on Glassfish with Toplink

May 8th, 2010

In my last post, i talked about developing a Dynamic JSF application with MySQL on JBoss with simple JDBC connection.

In this post, i am going to talk about a sample application with

- JSF

- Netbeans 6.8

- Glassfish Application Server

- MySQL Database

- Persistence API (Provider Toplink)

About the application

This would be a simple application which performs the following

- Insert Person Data into the database

- Fetch the person list from the database

The key difference over here is that we are going to use Java Persistence API over here to make the transactions.

First of all we need to understand as what is Java Persistence API.  As per the sun here is a very good definition for JPA.

The Java Persistence API is a POJO persistence API for object/relational mapping. It contains a full object/relational mapping specification supporting the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database. It supports a rich, SQL-like query language (which is a significant extension upon EJB QL) for both static and dynamic queries. It also supports the use of pluggable persistence providers.

Thus with the evolution of Java Persistence API, a standard of persistence framework has been set and many vendors are providing the implementation of the API and toplink is the open-source community edition of Oracle’s TopLink product.

Implementation

- In Netbeans, Create a Java Web project called TestPersonApplication and select the JSF framework while creating it. The folder structure would be created.

- After that create a mysql database,  in my case i call it jsfperson with table as person. The person table would have id (int), firstname (varchar) and lastname (varchar) as the fields

- Run the Glassfish Application Server and from services tab, against the server click “View Admin Console

Connection Pool Creation and JDBC resource creation

- After the admin console is loaded, click on JDBC and JDBC resources would be displayed

- Under Connection Pool, Click on Add a New Pool

- Enter Name, Resource Type as javax.sql.Datasource and Vendor as MySql and click on Next

- On the next screen, add the properties User, portnumber (3306), databaseName (jsfperson), Password, driverClass (com.mysql.jdbc.Driver), URL (jdbc:mysql://localhost:3306/jsfperson) and serverName(localhost) and click on Finish

- After Finish, click on Ping to check the connection, if the ping is successfully, your pool is created perfectly

- Now under JDBC resources, Click on “New”

- Enter the JNDI name and select the pool you created above (By default, when you again run the server, it creates a pool like mysql_jsfperson_rootPool, check that :) ) and click on Save

- After the save check sun-resources.xml under Server Resources and you will see the configuration

Creation of Entity Class

- Coming to Netbeans again, under Source Packages folder, create a package called com.domain

- Right click on the folder and select New – >Entity class from Database

- Select the datasource as jsfperson (Which you added earlier) and it will retrieve the database schema

- Select the table and Click on Add and than click on Next

- On next screen, it would show you the details for Person Entity and click on Finish

- The object would be created with Annotations for the mapping between Entity fields and Database field. The generated code would go like this

@Id
@Basic(optional = false)
@Column(name = “id”)
private Integer id;
@Column(name = “firstname”)
private String firstname;
@Column(name = “lastname”)
private String lastname;

The class would implement Serializable interface with getter, setter methods for the fields, equals method and toString Method. In addition, the queries would be generated as follows

@Entity
@Table(name = “person”)
@NamedQueries({
@NamedQuery(name = “Person.findAll”, query = “SELECT p FROM Person p”),
@NamedQuery(name = “Person.findById”, query = “SELECT p FROM Person p WHERE p.id = :id”),
@NamedQuery(name = “Person.findByFirstname”, query = “SELECT p FROM Person p WHERE p.firstname = :firstname”),
@NamedQuery(name = “Person.findByLastname”, query = “SELECT p FROM Person p WHERE p.lastname = :lastname”)
})

Check the @Entity and @Table annotation (Here the mapping starts) !!

Creation of Persistence Unit

- Right click on the project and select New -> Other -> Persistence ->Persistence Unit

- Enter Name, persistence provider which is Toplink and datasource created (jsfperson)

- Click on Finish and a file called persistence.xml would be created under configuration with transaction type as JTA

- Enter the class for which this PU would be used.  The xml would go like

<?xml version=”1.0″ encoding=”UTF-8″?>
<persistence version=”1.0″ xmlns=”http://java.sun.com/xml/ns/persistence” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd”>
<persistence-unit name=”TestJSFApplicationPU” transaction-type=”JTA”>
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<jta-data-source>jsfperson</jta-data-source>
<class>com.domain.Person</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties/>
</persistence-unit>

</persistence>

Creation of JSF Managed Bean

- Create a folder called com.testjsf under Sources Folder

- Right click on it and select New Jsf Managed Bean called PersonBean with configuration file as faces-config.xml under WEB-INF

- Declare two variables named Person (Entity Object ) and personList

- Create the getter and setter method for the variables

Creation of Data Access Object

Now we will make the connection class using DAO (data access object) design pattern

- Create a package called com.dao and create a class called PersonDAO

- The class would look like the following

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.dao;

import com.domain.Person;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
*
* @author Shashank
*/
public class PersonDAO {

public void insertData(Person p){

EntityManagerFactory emf = Persistence.createEntityManagerFactory(”TestJSFApplicationPU”);
EntityManager em= emf.createEntityManager();

try
{
em.getTransaction().begin();
em.persist(p);
em.getTransaction().commit();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
em.close();
}
}

public List getPersonList() {
List empList=null;
EntityManagerFactory emf = Persistence.createEntityManagerFactory(”TestJSFApplicationPU”);
EntityManager em= emf.createEntityManager();

try
{
Query q= em.createNamedQuery(”Person.findAll”);
empList= q.getResultList();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
em.close();
}
return empList;
}
}

In the above class there are few things to note

- JPA provides a class called EntityManagerFactory identified by persistence unit created above which manages all the transaction handling

- For example, to insert the data assuming Person object is there

a) Create a EntityManagerFactory

b) Create a Entity Manager

c) Begin transaction with em.getTransaction().begin()

d) call the persist function with person object as the argument. This statement would insert the data into the database

e) Finally commit is called

After creating the class, come back to PersonBean class and in the constructor for it, instantiate Person and Personlist (by calling PersonDAO getPersonList method). The constructor would go like

public PersonBean() {
person= new Person();

PersonDAO pDao= new PersonDAO();
personList = pDao.getPersonList();
}

Add two methods to it for adding a person and listing all persons which are as follows

public String addPerson()
{
PersonDAO pDao= new PersonDAO();
pDao.insertData(this.person);
this.setPersonList(pDao.getPersonList());
return “greeting“;
}

public String getAllPersonList()
{
PersonDAO pDao= new PersonDAO();
this.setPersonList(pDao.getPersonList());

return “go_person_list“;
}

Ok, now you are done with back end part. Keep the last two return statement in mind. I would discuss about them in the post below.

Front End with JSF

In the front end, add a file addPerson.jsp with firstname and lastname. The JSF part of it would go like

<f:view>
<h1>
<h:outputText value=”#{msg.inputname_header}”/>
</h1>
<h:form id=”helloForm”>
<h:outputText value=”#{msg.prompt}”/>
<h:inputText value=”#{personBean.person.firstname}” />
<h:inputText value=”#{personBean.person.lastname}” />
<h:commandButton action=”#{personBean.addPerson}” value=”#{msg.button_text}” />
<h:commandLink action=”go_person_list” value=”Show all persons”/>
</h:form>
</f:view>

Note that against the button action is mapped to addPerson method in the bean class.  The “h” and “f” tags are html and core tag libraries for JSF.

faces-config.xml

- Person bean is already added

- Add person as the managed property for it as

<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>com.testjsf.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>person</property-name>
<property-class>com.domain.Person</property-class>
<value>#{person}</value>
</managed-property>
</managed-bean>

This is how the person object is accessed under personbean in the jsf.

Handling Navigation

- Add the navigation rule as follows

<navigation-rule>
<from-view-id>/welcomeJSF.jsp</from-view-id>
<navigation-case>
<from-outcome>greeting</from-outcome>
<to-view-id>/personlist.jsp</to-view-id>
</navigation-case>
<from-view-id>/welcomeJSF.jsp</from-view-id>
<navigation-case>
<from-outcome>go_person_list</from-outcome>
<to-view-id>/personlist.jsp</to-view-id>
</navigation-case>
</navigation-rule>

- On submission of form, addMethod is called. If you see the last statement given above, on return “greeting” , the flow would go to first navigation rule with from view as welcomeJSF.jsp and action as greeting thus personlist.jsp would be called and loaded.

- The person list file would go like

<f:view>
<h:form>
<h:dataTable value=”#{personBean.personList}” var=”item”>
<h:column>
<f:facet name=”header”>
<h:outputText value=”Id”/>
</f:facet>
<h:outputText value=”#{item.id}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”First Name”/>
</f:facet>
<h:outputText value=”#{item.firstname}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”Last Name”/>
</f:facet>
<h:outputText value=”#{item.lastname}”/>
</h:column>

</h:dataTable>
</h:form>
</f:view>

In the file above, when {personBean.personList} is called, personBean is invoked and in the constructor, the latest person list is set. Thus on calling getter for personList, it returns the latest list after addition.

Thus you can develop the sample application using JPA with JSF in netbeans.

Thanks,

Ushainformatique Development Team

Dynamic JSF Application with MySql on JBoss 4.2.2 GA

March 21st, 2010

I have created a small JSF application (Employer Management) with MySQL as database on JBoss 4.2.2 GA in Netbeans 6.8.

These are the steps that need to be followed

1) Copy the mysql driver class (mysql-connector-java-5.1.6-bin.jar) which comes with Netbeans and located under {INSTALL DIR}/NetBeans 6.8/ide12/modules/ext to {INSTALL DIR}/server/default/lib. You don’t need to have the driver in your classpath.

2) Go to  {INSTALL DIR}/docs/examples, copy the mysql-ds.xml and copy it to {INSTALL DIR}/server/default/deploy. Change the database settings as per your configuration

3) Go to the services and (re)start the Application Server

4) Come back to netbeans, create a new project under category “Java Web”

5) Create a Managed Bean called “Employer” with member variables (id, firstname, lastname,phone and email) and corresponding getter and setter methods

6) Create a Backing Bean called EmployerFormBean with two variables

a) Employer

b) EmployerList

7) Create the getter setter for the above two variables and initialize the employerList by calling the getEmployerList function in EmployerDAO which is discussed later

8) Add method called addEmployer with its code as follows

EmployerDAO empDAO = new EmployerDAO();
empDAO.insertData(this.getEmployer());
return “go_insert_data”;

9) The configuration for Managed Bean, Backing Bean and “go_insert_data” should be made in faces-config.xml

<managed-bean>
<managed-bean-name>employerBean</managed-bean-name>
<managed-bean-class>com.testjsf.EmployerFormBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>employer</property-name>
<property-class>com.domain.Employer</property-class>
<value>#{employer}</value>
</managed-property>
</managed-bean>
<managed-bean>
<managed-bean-name>employer</managed-bean-name>
<managed-bean-class>com.domain.Employer</managed-bean-class>
<managed-bean-scope>none</managed-bean-scope>
</managed-bean>

<from-view-id>/employer.jsp</from-view-id>
<navigation-case>
<from-outcome>go_insert_data</from-outcome>
<to-view-id>/employerlist.jsp</to-view-id>
</navigation-case>

10) As you see, the database operations are performed inside DAO. The method insertData would be as follows

InitialContext ctx = new InitialContext();
//DataSource ds = (DataSource) ctx.lookup(”jdbc/jsfperson”);
DataSource ds = (DataSource) ctx.lookup(”java:/MySqlDS”);
conn = ds.getConnection();
String query = “insert into employer(firstname,lastname,email,phone) values (?,?,?,?)”;
//String query = “insert into employer(firstname,lastname,email,phone) values (’Mayank’,'Singhai’,'123456′,’abc@yahoo.com’)”;
stmt = conn.prepareStatement(query);
stmt.setString(1, emp.getFirstname());
stmt.setString(2, emp.getLastname());
stmt.setString(3, emp.getEmail());
stmt.setString(4, emp.getPhone());
stmt.executeUpdate();

11) While doing the JNDI lookup in JBoss call it as “java:/{dsname}” as defined in mysql-ds.xml

12) After insert, populate the employerList again in the backing bean before redirecting

12) Similarly create the getEmployerList function to get the list of employers

13) Now create two jsp

a) employer.jsp where form to insert data for the employer. The fields here are bind to the employer object in employerbean. The structure is as

<h:form id=”EmployerForm”>
<h:outputLabel value=”#{msg.firstname}”/> <h:inputText value=”#{employerBean.employer.firstname}”/>
<h:outputLabel value=”#{msg.lastname}”/> <h:inputText value=”#{employerBean.employer.lastname}”/>
<h:outputLabel value=”#{msg.phone}”/> <h:inputText value=”#{employerBean.employer.phone}”/>
<h:outputLabel value=”#{msg.email}”/> <h:inputText value=”#{employerBean.employer.email}”/>
<h:commandButton action=”#{employerBean.addEmployer}” value=”Submit”/>
<h:commandLink action=”show_emp_data” value=”Show all employers”/>
</h:form>

b) employerlist.jsp To display the list of employers. In this use the dataTable concept of JSF which is as follows

<h:form>
<h:dataTable value=”#{employerBean.empList}” var=”item”>
<h:column>
<f:facet name=”header”>
<h:outputText value=”Employee No.”/>
</f:facet>
<h:outputText value=”#{item.id}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”First Name”/>
</f:facet>
<h:outputText value=”#{item.firstname}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”Last Name”/>
</f:facet>
<h:outputText value=”#{item.lastname}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”Email”/>
</f:facet>
<h:outputText value=”#{item.email}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”Phone”/>
</f:facet>
<h:outputText value=”#{item.phone}”/>
</h:column>

</h:dataTable>
</h:form>

16) Compile the code and run employer.jsp. On successful insertion, employerlist with newly inserted record would be displayed.

JDBC Connection with Glassfish and MySQL on Netbeans 6.8

March 19th, 2010

This is a small proof of concept that we have done for creating the JDBC connection with MySql Database and  Glassfish Application Server. This is performed on Netbeans 6.8 which seems to be working best for our team.

These are the steps that need to be followed

1) Copy the mysql driver class (mysql-connector-java-5.1.6-bin.jar) which comes with Netbeans and located under {INSTALL DIR}/NetBeans 6.8/ide12/modules/ext to {INSTALL DIR}/glassfish/domains/domain1/lib/ext. You don’t need to have the driver in your classpath.

2) Go to the services and (re)start the Application Server

3) Right click on Server Name and click on View Admin Console

4) After admin console loads, click on Resources in left nav, JDBC resources and connection pools will be displayed

5) Create a Connection pool with resource type as javax.sql.DataSource and Datasource class name as com.mysql.jdbc.jdbc2.optional.MysqlDataSource ( This will be present in jar copied in step 1). Under additional attributes, add user,password, databaseName.

6) Always keep the ping enabled to check the connectivity

7) On Save, ping would be executed. Based on the status (Success or failure) message would be displayed

8) If the ping is successful,  create a JDBC resource with name as jdbc/{yourname}. In glassfish always give jdbc name starting with ‘jdbc/’.

9) Come back to netbeans, create a new project under category “Java Web”

10) In the Source Package Folder, create a package

11) Right click on package name and select new “Servlet”

12) After the servlet is created, in the try block within doProcess method, paste the following code

InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(”jdbc/{yourjdbcname}”);

Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();

13) The above code gets the datasource connection in the JDBC pool created from Admin console

14) Execute a query which in my case is

ResultSet rs = stmt.executeQuery(”select * from person”);

out.println(”<html>”);
out.println(”<head>”);
out.println(”<title>Servlet POC on Glassfish</title>”);

while(rs.next())
{
out.println(”<h1>First Name is ” + rs.getString(”firstname”) + “</h1>”);
out.println(”<h1>Last Name is ” + rs.getString(”lastname”) + “</h1>”);
}
out.println(”</body>”);
out.println(”</html>”);

stmt.close();
stmt=null;
conn.close();
conn=null;

15) Always close the connections at the end

16) Compile the code and run it. The result would be displayed