Integration of JSF2 + EJB3 + JPA2 + JavaDB(Derby) PART-1

I was working with one of my friends and had a requirement to call an EJB in Managed bean of JSF with annotations. Initially i had a very tough time to write the code of JSF and calling EJB with JNDI global names, later on i was successful and here is the result of my research to pull data from database and to show in browser.

Customer.java:

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

package com.spark.ejb.model;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
*
* @author Sony
*/
@Entity
@Table(name = “CUSTOMER”)
@NamedQueries({
@NamedQuery(name = “Customer.findAll”, query = “SELECT c FROM Customer c”),
@NamedQuery(name = “Customer.findAllDiscountCodes”, query = “SELECT c.discountCode FROM Customer c”),
@NamedQuery(name = “Customer.findByCustomerId”, query = “SELECT c FROM Customer c WHERE c.customerId = :customerId”),
@NamedQuery(name = “Customer.findByZip”, query = “SELECT c FROM Customer c WHERE c.zip = :zip”),
@NamedQuery(name = “Customer.findByName”, query = “SELECT c FROM Customer c WHERE c.name = :name”),
@NamedQuery(name = “Customer.findByAddressline1”, query = “SELECT c FROM Customer c WHERE c.addressline1 = :addressline1”),
@NamedQuery(name = “Customer.findByAddressline2”, query = “SELECT c FROM Customer c WHERE c.addressline2 = :addressline2”),
@NamedQuery(name = “Customer.findByCity”, query = “SELECT c FROM Customer c WHERE c.city = :city”),
@NamedQuery(name = “Customer.findByState”, query = “SELECT c FROM Customer c WHERE c.state = :state”),
@NamedQuery(name = “Customer.findByPhone”, query = “SELECT c FROM Customer c WHERE c.phone = :phone”),
@NamedQuery(name = “Customer.findByFax”, query = “SELECT c FROM Customer c WHERE c.fax = :fax”),
@NamedQuery(name = “Customer.findByEmail”, query = “SELECT c FROM Customer c WHERE c.email = :email”),
@NamedQuery(name = “Customer.findByCreditLimit”, query = “SELECT c FROM Customer c WHERE c.creditLimit = :creditLimit”)})
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = “CUSTOMER_ID”)
private Integer customerId;
@Basic(optional = false)
@Column(name = “ZIP”)
private String zip;
@Column(name = “NAME”)
private String name;
@Column(name = “ADDRESSLINE1”)
private String addressline1;
@Column(name = “ADDRESSLINE2”)
private String addressline2;
@Column(name = “CITY”)
private String city;
@Column(name = “STATE”)
private String state;
@Column(name = “PHONE”)
private String phone;
@Column(name = “FAX”)
private String fax;
@Column(name = “EMAIL”)
private String email;
@Column(name = “CREDIT_LIMIT”)
private Integer creditLimit;
@JoinColumn(name = “DISCOUNT_CODE”, referencedColumnName = “DISCOUNT_CODE”)
@ManyToOne(optional = false)
private DiscountCode discountCode;

public Customer() {
}

public Customer(Integer customerId) {
this.customerId = customerId;
}

public Customer(Integer customerId, String zip) {
this.customerId = customerId;
this.zip = zip;
}

public Integer getCustomerId() {
return customerId;
}

public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}

public String getZip() {
return zip;
}

public void setZip(String zip) {
this.zip = zip;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddressline1() {
return addressline1;
}

public void setAddressline1(String addressline1) {
this.addressline1 = addressline1;
}

public String getAddressline2() {
return addressline2;
}

public void setAddressline2(String addressline2) {
this.addressline2 = addressline2;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getFax() {
return fax;
}

public void setFax(String fax) {
this.fax = fax;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public Integer getCreditLimit() {
return creditLimit;
}

public void setCreditLimit(Integer creditLimit) {
this.creditLimit = creditLimit;
}

public DiscountCode getDiscountCode() {
return discountCode;
}

public void setDiscountCode(DiscountCode discountCode) {
this.discountCode = discountCode;
}

/**
* Created manually to cater for use e.g. by the dropdown list
* @return Character the discount code
*/
public Character getDiscount()
{
return this.discountCode.getDiscountCode();
}

/**
* Created manually to cater for use e.g. by the dropdown list
* @param code discount code
*/
public void setDiscount(Character code)
{
this.discountCode = new DiscountCode(code);
}

@Override
public int hashCode() {
int hash = 0;
hash += (customerId != null ? customerId.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning – this method won’t work in the case the id fields are not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.customerId == null && other.customerId != null) || (this.customerId != null && !this.customerId.equals(other.customerId))) {
return false;
}
return true;
}

@Override
public String toString() {
return “com.spark.ejb.model.Customer[customerId=” + customerId + “]”;
}

}

DiscountCode.java

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

package com.spark.ejb.model;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
*
* @author Sony
*/
@Entity
@Table(name = “DISCOUNT_CODE”)
@NamedQueries({
@NamedQuery(name = “DiscountCode.findAll”, query = “SELECT d FROM DiscountCode d”),
@NamedQuery(name = “DiscountCode.findByDiscountCode”, query = “SELECT d FROM DiscountCode d WHERE d.discountCode = :discountCode”),
@NamedQuery(name = “DiscountCode.findByRate”, query = “SELECT d FROM DiscountCode d WHERE d.rate = :rate”)})
public class DiscountCode implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = “DISCOUNT_CODE”)
private Character discountCode;
@Column(name = “RATE”)
private BigDecimal rate;
@OneToMany(cascade = CascadeType.ALL, mappedBy = “discountCode”)
private Collection<Customer> customerCollection;

public DiscountCode() {
}

public DiscountCode(Character discountCode) {
this.discountCode = discountCode;
}

public Character getDiscountCode() {
return discountCode;
}

public void setDiscountCode(Character discountCode) {
this.discountCode = discountCode;
}

public BigDecimal getRate() {
return rate;
}

public void setRate(BigDecimal rate) {
this.rate = rate;
}

public Collection<Customer> getCustomerCollection() {
return customerCollection;
}

public void setCustomerCollection(Collection<Customer> customerCollection) {
this.customerCollection = customerCollection;
}

@Override
public int hashCode() {
int hash = 0;
hash += (discountCode != null ? discountCode.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning – this method won’t work in the case the id fields are not set
if (!(object instanceof DiscountCode)) {
return false;
}
DiscountCode other = (DiscountCode) object;
if ((this.discountCode == null && other.discountCode != null) || (this.discountCode != null && !this.discountCode.equals(other.discountCode))) {
return false;
}
return true;
}

@Override
public String toString() {
return “com.spark.ejb.model.DiscountCode[discountCode=” + discountCode + “]”;
}

}

Now the coding of Enterprise App starts, which include EJB(session beans) and MDB. As of EJB3 we dont have to write the local and remote interfaces(Latest Enhancement).

CustomerSession.java

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

package com.spark.ejb.sessionbeans;

import com.spark.ejb.model.Customer;
import com.spark.ejb.model.DiscountCode;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
*
* @author Sony
*/
@Stateless
@LocalBean
public class CustomerSession {
@Resource(name = “jms/NotificationQueue”)
private Queue notificationQueue;
@Resource(name = “jms/NotificationQueueFactory”)
private ConnectionFactory notificationQueueFactory;
@PersistenceContext(unitName = “CustomerApp-ejbPU”)
private EntityManager em;

public void persist(Object object) {
em.persist(object);
}

public List<Customer> retrieve() {
Query query = em.createNamedQuery(“Customer.findAll”);
return query.getResultList();
}

public Customer update(Customer customer) {

Customer updated = em.merge(customer);
try {
sendJMSMessageToNotificationQueue(updated);
} catch (Exception e) {
Logger.getLogger(CustomerSession.class.getName()).log(Level.SEVERE, null, e);
}

System.out.println(“Customer details updated Successfully !”);
return updated;
}

/**
* Included here for convenience rather than creating a new Session Bean
* @return List<DiscountCode>
*/
public List<DiscountCode> getDiscountCodes()
{
Query query = em.createNamedQuery(“DiscountCode.findAll”);
return query.getResultList();
}

private Message createJMSMessageForjmsNotificationQueue(Session session, Object messageData) throws JMSException {
// TODO create and populate message to send

ObjectMessage objectMessage = session.createObjectMessage();
objectMessage.setObject((Serializable)messageData);
return objectMessage;
}

private void sendJMSMessageToNotificationQueue(Object messageData) throws JMSException {
Connection connection = null;
Session session = null;
try {
connection = notificationQueueFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(notificationQueue);
messageProducer.send(createJMSMessageForjmsNotificationQueue(session, messageData));
} finally {
if (session != null) {
try {
session.close();
} catch (JMSException e) {
Logger.getLogger(this.getClass().getName()).log(Level.WARNING, “Cannot close session”, e);
}
}
if (connection != null) {
connection.close();
}
}
}
}

NotificationBean.java(MDB)

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

package com.spark.ejb.mdb;

import com.spark.ejb.model.Customer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

/**
*
* @author Sony
*/
@MessageDriven(mappedName = “jms/NotificationQueue”, activationConfig =  {
@ActivationConfigProperty(propertyName = “acknowledgeMode”, propertyValue = “Auto-acknowledge”),
@ActivationConfigProperty(propertyName = “destinationType”, propertyValue = “javax.jms.Queue”)
})
public class NotificationBean implements MessageListener {

public NotificationBean() {
}

public void onMessage(Message message) {
try {
Object object = ((ObjectMessage) message).getObject();
if(object != null){
Customer customer = (Customer)object;
StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append(“CustomerName = “);
stringBuilder.append(customer.getName());

System.out.println(stringBuilder.toString());
}
} catch (JMSException ex) {
Logger.getLogger(NotificationBean.class.getName()).log(Level.SEVERE, null, ex);
}
}

}

Advertisements

One thought on “Integration of JSF2 + EJB3 + JPA2 + JavaDB(Derby) PART-1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s