Sunday, February 24, 2013

Part 9: How to create and configure JNDI DataSource for MySQL in GlassFish 3.1.1 Server


In this part we'll create JNDI data source name to work with our EJBs (Enterprise Java Beans).
First of all, copy mysql-connector-java-5.1.18-bin.jar file, which you have downloaded in the part 7 of this tutorial, in your GlassFish lib folder. The path should look like this: glassfish3\glassfish\lib. Restart your eclipse and do the following:
In the lower corner of your Eclipse window, right-click GlassFish 3.1.1 under Servers tap and click GlassFish -> View Admin Console.
This will open Admin Console in the browser window. Once its open, in the left-hand side panel underResources, click on JDBC and then JDBC Connection Pools. In the right hand-side click on new button.
In New JDBC Connection Pool window, give MYSQL_Pool as Pool Name, selectjavax.sql.DataSource as Resource Type, and MySQL as Database Driver Vendor. On the right upper corner click Next button.
In the log list of additional properties of the next window, find the following properties and fill them with as follows:
Url: jdbc:mysql://:3306/test
URL: jdbc:mysql://:3306/test
Port: 3306
DatabaseName: your database name (in our case test)
ServerName: localhost
User:root
Password: your password, which you have created in part 6
Click finish and you will see your pool in the list now.
Click on ping to test if the pool is created successfully. If not successful, check all the properties again.
Under the JDBC click on JDBC Resources, click new. In New JDBC Resource window, select MySQL_Pool from Pool Name, and give jdbc/testdsn as JNDI name; dont't forget to click Ok on the upper right corner.
Now that we have created our DataSource, we'll configure our persistence.xml file to access this Data Source. Open your persistence.xml, which you will find under JPA Content folder.
In the navigation options of xml file click on Source.
Make the file look like following:

persistence.xml



<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">

 <persistence-unit name="testPU" transaction-type="JTA">
  <jta-data-source>jdbc/testdsn</jta-data-source>
  <class>datamodel.entities.Customer</class>
 </persistence-unit>
</persistence>


In the code above with have specified a persistence unit named testPU. As transaction type we have used JTA (Java Transaction API). as JTA DataSource, we have specified jdbc/testdsn, that we have created above, and finally we have specified our entity class Customer.java, which is to be mapped.
Now we'll create our EJB. In order to create enterprise java bean, right click on src package and click New -> Other. From Wizards' list select Session Bean (EJB 3.x) under EJB and click Next.
Give 'ejb.beans' as package name. Give CustomerEJB as class Name. Select 'State type' as 'Stateless' and click finish.
Delete the default constructor and make the code look like following; in the code import all the necessary packages.

CustomerEJB.java



package ejb.beans;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import datamodel.entities.Customer;

/**
 * Session Bean implementation class CustomerEJB
 */
@Stateless
@LocalBean
public class CustomerEJB {

    @PersistenceContext(unitName = "testPU")
    EntityManager em;
    
    public List<Customer> customerList = new ArrayList<Customer>();
    
    public List<Customer> findAll() {
     
     TypedQuery<Customer> query = em.createQuery("select c from Customer c", Customer.class);
     customerList = query.getResultList();
     return customerList;
     
    }

}


So simple as that. EJBs has made life easier for us. In the above code, we have created a persistence context, that will take care of our entities, i.e. entity classes, and then we have create our entity manager, that will perform actions on entity classes. You don't need to open and close and commit your transactions anymore. Entity manager will take care of all that.
In our function which return a list off our customers, we have created a query of type Customer using em.createQuery. In createQuery we have used JPQL (Java Persistence Query Language). JPQL is standard query language to write queries in JPA. The simplest form is select a from Customer a, and we have used c for our Customer entity instead of a. Keep in mind that this is not the name of customer table rather the name of Customer entity class, which starts with capital C. Then we have executed our query using query.getResultList and have saved results in customerList, and finally we have returned our customerList.
Now that, we have created our business logic, in which we have created our EJB class, we'll now create our web logic in which we'll create our managed bean to access findAll() method defined in our CustomerEJB.java class.
So, right click on src package and create an new class by clicking New -> class. Give the package name as web.beans. Give the class name as CustomerBean, and click finish.

CustomerBean.java




package web.beans;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import datamodel.entities.Customer;

import ejb.beans.CustomerEJB;

@ManagedBean (name = "customerBean")
@SessionScoped
public class CustomerBean {

 @EJB
 CustomerEJB customerEJB; 
 
 private List<Customer> customerList = new ArrayList<Customer>();

 public List<Customer> getCustomerList() {
  customerList = customerEJB.findAll();
  return customerList;
 }

 public void setCustomerList(List<Customer> customerList) {
  this.customerList = customerList;
 }

  
}



In the above code, we have injected our CustomerEJB by using the annotation @EJB. This allows us to access EJBs directly in our ManagedBean class. As you have seen we have called ourfindAll() method directly from CustomerEJB.java class.
In the next step we'll create our web page to display the list of our customers. So, click Next.

No comments:

Post a Comment