In my last post, I created the Entity class in the EJB Module project for the tutorial/project Car rental Enterprise Application.

A session bean encapsulates business logic that can be invoked programmatically by a client over local, remote, or web service client views. To access an application that is deployed on the server, the client invokes the session bean’s methods. The session bean performs work for its client, shielding it from complexity by executing business tasks inside the server.

A session bean is not persistent. (That is, its data is not saved to a database.) But with the help of the EntityManager class, Session beans can save data to a database.

Session Beans are of three types:

Stateful Session Beans:
The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client/bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state.

As its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it can have only one client, in the same way that an interactive session can have only one user. When the client terminates, its session bean appears to terminate and is no longer associated with the client.

The state is retained for the duration of the client/bean session. If the client removes the bean, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends, there is no need to retain the state.

Stateless Session Beans

A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client but only for the duration of the invocation. When the method is finished, the client-specific state should not be retained. Clients may, however, change the state of instance variables in pooled stateless beans, and this state is held over to the next invocation of the pooled stateless bean. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client. That is, the state of a stateless session bean should apply across all clients.

Because they can support multiple clients, stateless session beans can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients.

A stateless session bean can implement a web service, but a stateful session bean cannot.

 

Singleton Session Beans

A singleton session bean is instantiated once per application and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across and concurrently accessed by clients.

Singleton session beans offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean per application, as opposed to a pool of stateless session beans, any of which may respond to a client request. Like stateless session beans, singleton session beans can implement web service endpoints.

Singleton session beans maintain their state between client invocations but are not required to maintain their state across server crashes or shutdowns.

Applications that use a singleton session bean may specify that the singleton should be instantiated upon application startup, which allows the singleton to perform initialization tasks for the application. The singleton may perform cleanup tasks on application shutdown as well, because the singleton will operate throughout the lifecycle of the application.

Stateful session beans are appropriate if any of the following conditions are true.

  • The bean’s state represents the interaction between the bean and a specific client.
  • The bean needs to hold information about the client across method invocations.
  • The bean mediates between the client and the other components of the application, presenting a simplified view to the client.
  • Behind the scenes, the bean manages the work flow of several enterprise beans.

To improve performance, you might choose a stateless session bean if it has any of these traits.

  • The bean’s state has no data for a specific client.
  • In a single method invocation, the bean performs a generic task for all clients. For example, you might use a stateless session bean to send an email that confirms an online order.
  • The bean implements a web service.

Singleton session beans are appropriate in the following circumstances.

  • State needs to be shared across the application.
  • A single enterprise bean needs to be accessed by multiple threads concurrently.
  • The application needs an enterprise bean to perform tasks upon application startup and shutdown.
  • The bean implements a web service.

For the purpose of this tutorial/project, we shall be making use of a Stateless Session Bean.

To Create a Persistence Session Bean Class:

  • Open the EJB Module Netbeans project created in the previous post; Open Netbeans IDE, from the file menu, Click on Open Project and choose CarRental-ejb. Make sure the server is started.
  • Create a folder named setup inside EJB Module project and add wildfly datasource file inside the setup folder. Refer to this POST on how to create wildfly datasource xml file.
  • Create two Java packages in CarRental-ejb project named com.rental.bean and com.rental.remoteinterface respectively.
  • Create a Java Interface named rentalRemote inside com.rental.remoteinterface package where the business methods will be declared.
  • Create a Java Class named rentalBean inside com.rental.bean package that will implement rentalRemote Interface.

EJB session bean - geekshelm

  • Below is the source code inside the remote Interface:
package com.rental.remoteinterace;

import com.rental.entity.Info;
import java.util.List;
import java.util.Random;
import javax.ejb.Remote;
import javax.persistence.EntityManager;

/**
 *
 * @author STEINACOZ-PC
 */
@Remote
public interface rentalRemote {
    
    
    
    //Admin business methods
    void addNewCar(String carName, String model, String available, String category, String FilePath, String manu, String price, String year);
    void removeCar (String catalogueNumber);
    void updateCarinfo (Info info, String filePath, String price, String ref);
    List<Info> carStatus();
    
    
    String getStatusMsg();
    String getCarName();
    String getCarModel();
    String getCategory();
    String getFilepath();
    String getManu();
    float getCarPrice();
    String getCarYear();
    
    
    
    void search(String ref);
    
}

The business methods are declared in the remote interface; addNewCar() is where the entity manager persist method is invoked to store records to the database, the removeCar() is where the entityManager’s remove method is invoked to delete record from the database.

  • Below is the source code inside rentalBean class:
package com.rental.bean;

import com.rental.entity.Info;
import com.rental.remoteinterace.rentalRemote;
import java.util.Calendar;
import java.util.Date;

import java.util.List;
import java.util.Random;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author STEINACOZ-PC
 */
@Stateless
public class rentalBean implements rentalRemote{

    public rentalBean() {
    }
    
    @PersistenceContext(unitName="CarRental-ejbPU")
    private EntityManager em;
    Random rad = new Random();
    String status;
    
    String carName, carModel, carCategory, carImage, carYear;
    float carPrice;
    
     @Override
    public void addNewCar(String carName, String model, String available, String category, String FilePath, String manu, String price, String year) {
       
Info info = new Info();        
//generate catalogue Number
        String a = String.valueOf(rad.nextInt(9));
        String b = String.valueOf(rad.nextInt(9));
        String c = String.valueOf(rad.nextInt(9));
        String d = String.valueOf(rad.nextInt(9));
        String e = String.valueOf(rad.nextInt(9));
        String f = String.valueOf(rad.nextInt(9));
        
        String generatedNum = a + b + c + d + e + f + "-" + model.substring(0, 2);
       
        
        //persist
       
       info.setCarname(carName);
       info.setCarmodel(model);
       info.setAvailable(available);
       info.setCategory(category);
       info.setImage(FilePath);
       info.setManufacturer(manu);
       info.setPrice(Float.parseFloat(price));
       info.setYear(year);
        
        info.setRef(generatedNum);
      info.setExpecteddate(new Date());
        info.setAddeddate(new Date());
        em.persist(info);
        em.flush();
        status = "Operation successful";
        setStatusMsg(status);
    }
 

   
    
    private void setStatusMsg(String msg){
        status = msg;
    }

    @Override
    public String getStatusMsg(){
        return status;
    }
    
    @Override
    public void removeCar(String ref) {
        Info in = new Info();
        try{
       
        
        Query q = em.createNamedQuery("Info.findByRef");
     q.setParameter("ref", ref);
    
     in = (Info) q.getSingleResult();
     
     em.remove(in);
     this.status = "Operation Successful";
     this.setStatusMsg(status);
     
        }catch(NoResultException e){
      this.status = "This Car doesn't exist";
     this.setStatusMsg(status); 
     System.out.println(e.getMessage());
        }
     
    }

    @Override
    public void updateCarinfo(Info info, String filePath, String price, String ref) {
        
        Query qq = em.createNamedQuery("Info.findByRef");
        qq.setParameter("ref", ref);
        
        info = (Info) qq.getSingleResult();
        info.setPrice(Float.parseFloat(price));
        info.setImage(filePath);
        
        em.merge(info);
        em.flush();
        status = "Update Operation Successful";
        setStatusMsg(status);
    }

    @Override
    public List<Info> carStatus() {
return em.createQuery("From Info").getResultList();
    }

    @Override
    public void search(String ref) {
        Info inf;
        
     Query q = em.createNamedQuery("Info.findByRef");
     q.setParameter("ref", ref);
    
     inf = (Info) q.getSingleResult();
     
     setCaName(inf.getCarname());
     setCaModel(inf.getCarmodel());
     setCaPrice(inf.getPrice());
     setCaCategory(inf.getCategory());
     setCaYear(inf.getYear());
     setCaImg(inf.getImage());
     
    }
    
    public void setCaName (String n){
        this.carName = n;
    }
    
    public void setCaModel (String m){
        this.carModel = m;
    }
    public void setCaPrice (float p){
        this.carPrice = p;
    }
    public void setCaCategory (String c){
        this.carCategory = c;
    }
    public void setCaYear (String y){
        this.carYear = y;
    }
    public void setCaImg (String i){
        this.carImage = i;
    }

    @Override
    public String getCarName() {
        return this.carName;
    }

    @Override
    public String getCarModel() {
        return this.carModel;
    }

    @Override
    public String getCategory() {
        return this.carCategory;
    }

    @Override
    public String getFilepath() {
        return this.carImage;
    }

    @Override
    public String getManu() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public float getCarPrice() {
        return this.carPrice;
    }

    @Override
    public String getCarYear() {
        return this.carYear;
    }

   
    
}

To designate an Interface as remote, use the @Remote annotation, Remote Interface is used when the EJB client is in different enivornment where the EJB Session Bean is to be deployed while the @Local annotation is used when the EJB client is in the same environment where the EJB Session Bean is to be deployed.

@Remote
public interface rentalRemote {}

Another method that doesn’t involve anontation is:

public interface rentalRemote extends EJBHome {}

but interfaces written with EJB 3.0 doesn’t require EJBHome again, just use the @Remote annontation.

Entity Manager is a Persistence interface to do data operations like add/delete/update/find on persistent object (entity). It also helps to execute queries using Query interface.

Persistence Unit is used describes the properties of persistence mechanism. The persistence unit was generated when creating the Entity Class in the previous post.

I passed the persistence unit(persistence.xml) to the Entity manager using the @PersistenceContext annontation.

@PersistenceContext(unitName="CarRental-ejbPU")
   
private EntityManager em;

Finally, add jpa (jpa.jar) library to the EJB Module project. Changes will still be made to the business methods in this post.

LEAVE A REPLY

Please enter your comment!
Please enter your name here