Dynamic JSF application with MySQL on Glassfish with Toplink

May 8th, 2010 by Usha Informatique Team Leave a reply »

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

Advertisement

116 comments

  1. Thanks for the fantastic post. I will be sure to add your blog to my newsreader to keep up with your future posts. Being in the lighting business, it’s great to view things from a alternative viewpoint.

  2. Really great informative blog post here and I just wanted to comment & thank you for posting this. I’ve bookmarked youi blog and I’ll be back to read more in the future my friend! Also nice colors on the layout, it’s really easy on the eyes.

  3. Amazing post thanks!

    Sent via Blackberry

  4. Wow this takes me back. Like your blog design too.

  5. Great job on the blog, it looks wonderful. I am going to bookmark it and will make sure to check weekly

  6. vacuum mixer says:

    I agree with your point of view and I feel very attracted to it.

  7. You can learn anything if you have the help of a solid role model.

  8. you did a good job. I will come back. David

  9. Why didn’t I find this post earlier? Keep up the good work!

  10. Sell Aion says:

    Thanks for taking the time to write that, I found it very interesting. If you get a chance you should check my site as well. I hope you have a great day!

  11. A thoughtful insight and ideas I will use on my blog. You’ve obviously spent some time on this. Well done!

  12. loving this website, good thing I stumbled it for you on stumble upon.

  13. Nuby says:

    Thanks for taking the time to write that, I found it very educational. If you get a chance you should check my blog as well. I hope you have a nice day!

  14. Excellent post I must say.. Simple but yet interesting and engaging.. Keep up the awesome work!

  15. This is awesome poste for a long time i ‘ve ever read. Can i have your contact please? I have somthing to ask. Merci.

  16. I hope you have a great day! Very good article, well written and very thought out. I am looking forward to reading more of your posts in the future.

  17. There are some great ideas here. I must redesign my blog sometime. I am going to start from scratch this time I think.

  18. Toddler Cups says:

    Thanks for taking the time to write that, I found it very educational. If you get a chance you should check my blog as well. I hope you have a nice day!

Leave a Reply