Java/EJB3/Stateless Session Bean

Материал из Java эксперт
Перейти к: навигация, поиск

EJB Method With Interceptors

   <source lang="java">

File: Employee.java import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {

 private int id;
 private String firstName;
 private String lastName;
 @Id
 @GeneratedValue
 public int getId() {
   return id;
 }
 @PostRemove
 public void postRemove()
 {
    System.out.println("@PostRemove");
 }
 public void setId(int id) {
   this.id = id;
 }
 public String getFirstName() {
   return firstName;
 }
 public void setFirstName(String first) {
   this.firstName = first;
 }
 public String getLastName() {
   return lastName;
 }
 public void setLastName(String last) {
   this.lastName = last;
 }

}

File: EmployeeService.java import javax.ejb.Stateless; import javax.interceptor.Interceptors; @Stateless public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {

 public EmployeeService() {
 }
 
 @Interceptors(Profiler.class)
 public void doAction() {
   System.out.println("do Action");
 }

}

File: EmployeeServiceLocal.java

import java.util.Collection; import javax.ejb.Local; @Local public interface EmployeeServiceLocal {

   public void doAction();

}

File: EmployeeServiceRemote.java


import java.util.Collection; import javax.ejb.Remote; @Remote public interface EmployeeServiceRemote{

 public void doAction();  

}

File: Profiler.java import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; public class Profiler {

 @AroundInvoke
 public Object profile(InvocationContext invocation) throws Exception {
   long startTime = System.currentTimeMillis();
   try {
     return invocation.proceed();
   } finally {
     long endTime = System.currentTimeMillis() - startTime;
     System.out.println("Method " + invocation.getMethod() + " took " + endTime + " (ms)");
   }
 }

}

File: Main.java import java.util.Date; import javax.naming.InitialContext;

public class Main {

 public static void main(String[] a) throws Exception {
   EmployeeServiceRemote service = null;
   // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
   // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
   service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeService/remote");
   
   


   service.doAction();
 }

}

File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099


      </source>
   
  
 
  



EJB Tutorial from JBoss: stateless session bean

   <source lang="java">

File: Calculator.java /*

* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

package org.jboss.tutorial.stateless.bean; public interface Calculator {

  int add(int x, int y);
  int subtract(int x, int y);

}

File: CalculatorBean.java /*

* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

package org.jboss.tutorial.stateless.bean; import javax.ejb.Stateless; @Stateless public class CalculatorBean implements CalculatorRemote, CalculatorLocal {

  public int add(int x, int y)
  {
     return x + y;
  }
  public int subtract(int x, int y)
  {
     return x - y;
  }

}

File: CalculatorLocal.java /*

* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

package org.jboss.tutorial.stateless.bean; import javax.ejb.Local;

@Local public interface CalculatorLocal extends Calculator { }

File: CalculatorRemote.java /*

* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

package org.jboss.tutorial.stateless.bean; import javax.ejb.Remote;

@Remote public interface CalculatorRemote extends Calculator { } File: Client.java /*

* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

package org.jboss.tutorial.stateless.client; import org.jboss.tutorial.stateless.bean.Calculator; import org.jboss.tutorial.stateless.bean.CalculatorRemote; import javax.naming.InitialContext; public class Client {

  public static void main(String[] args) throws Exception
  {
     InitialContext ctx = new InitialContext();
     Calculator calculator = (Calculator) ctx.lookup("CalculatorBean/remote");
     System.out.println("1 + 1 = " + calculator.add(1, 1));
     System.out.println("1 - 1 = " + calculator.subtract(1, 1));
  }

}


      </source>
   
  
 
  



EJB Tutorial from JBoss: stateless session bean deployment descriptor

   <source lang="java">

File: ejb-jar.xml <?xml version="1.0" encoding="UTF-8"?> <ejb-jar

       xmlns="http://java.sun.ru/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.ru/xml/ns/javaee
                           http://java.sun.ru/xml/ns/javaee/ejb-jar_3_0.xsd"
       version="3.0">
  <description>JBoss Stateless Session Bean Tutorial</description>
  <display-name>JBoss Stateless Session Bean Tutorial</display-name>
  <enterprise-beans>
     <session>
        <ejb-name>Calculator</ejb-name>
        <remote>org.jboss.tutorial.stateless_deployment_descriptor.bean.CalculatorRemote</remote>
        <local>org.jboss.tutorial.stateless_deployment_descriptor.bean.CalculatorLocal</local>
        <ejb-class>org.jboss.tutorial.stateless_deployment_descriptor.bean.CalculatorBean</ejb-class>
        <session-type>Stateless</session-type>
        <transaction-type>Container</transaction-type>
     </session>
  </enterprise-beans>

</ejb-jar>

File: jboss.xml <?xml version="1.0"?> <jboss

       xmlns="http://java.sun.ru/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.ru/xml/ns/javaee
                           http://www.jboss.org/j2ee/schema/jboss_5_0.xsd"
       version="3.0">
  <enterprise-beans>
     <session>
        <ejb-name>Calculator</ejb-name>
        <jndi-name>org.jboss.tutorial.stateless_deployment_descriptor.bean.CalculatorRemote</jndi-name>
        <local-jndi-name>org.jboss.tutorial.stateless_deployment_descriptor.bean.CalculatorLocal</local-jndi-name>
     </session>
  </enterprise-beans>

</jboss>


      </source>
   
  
 
  



Mark One Method With Two Lifecycle Annotations

   <source lang="java">

File: EmployeeBean.java

import javax.annotation.PostConstruct; import javax.ejb.PostActivate; import javax.ejb.Stateless; @Stateless public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote {

 public EmployeeBean() {
 }
 @PostConstruct
 @PostActivate 
 public void doAction() {
 }

}

File: EmployeeServiceLocal.java

import javax.ejb.Local; @Local public interface EmployeeServiceLocal {

 public void doAction();

}

File: EmployeeServiceRemote.java import javax.ejb.Remote;

@Remote public interface EmployeeServiceRemote {

 public void doAction();


}

File: Employee.java

import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {

 private int id;
 private String firstName;
 private String lastName;
 @Id
 @GeneratedValue
 public int getId() {
   return id;
 }
 @PostRemove
 public void postRemove()
 {
    System.out.println("@PostRemove");
 }
 public void setId(int id) {
   this.id = id;
 }
 public String getFirstName() {
   return firstName;
 }
 public void setFirstName(String first) {
   this.firstName = first;
 }
 public String getLastName() {
   return lastName;
 }
 public void setLastName(String last) {
   this.lastName = last;
 }

}

File: Main.java import javax.ejb.EJB; import javax.naming.InitialContext;

public class Main {

 public static void main(String[] a) throws Exception {
   EmployeeServiceRemote service = null;
   // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
   // service = (HelloService)new
   // InitialContext().lookup("java:comp/env/ejb/HelloService");
   service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeBean/remote");
   service.doAction();
   
 }

}

File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099


      </source>
   
  
 
  



One Stateless Session Bean Call Another Stateless Bean

   <source lang="java">

File: AnotherBeanLocal.java

public interface AnotherBeanLocal {

 public void doAnother();

}

File: Employee.java

import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove;

@Entity public class Employee implements java.io.Serializable {

 private int id;
 private String firstName;
 private String lastName;
 @Id
 @GeneratedValue
 public int getId() {
   return id;
 }
 @PostRemove
 public void postRemove()
 {
    System.out.println("@PostRemove");
 }
 public void setId(int id) {
   this.id = id;
 }
 public String getFirstName() {
   return firstName;
 }
 public void setFirstName(String first) {
   this.firstName = first;
 }
 public String getLastName() {
   return lastName;
 }
 public void setLastName(String last) {
   this.lastName = last;
 }

}

File: EmployeeBean.java import javax.ejb.EJB; import javax.ejb.EJBException; import javax.ejb.Stateless; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; @Stateless @EJB(name = "audit", beanInterface = AnotherBeanLocal.class) public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote {

 public EmployeeBean() {
 }
 public void doAction() {
   System.out.println("doAction");
   try {
     Context ctx = new InitialContext();
     AnotherBeanLocal a = (AnotherBeanLocal) ctx.lookup("java:comp/env/audit");
     a.doAnother();
   } catch (NamingException e) {
     throw new EJBException(e);
   }
 }

}

File: EmployeeServiceLocal.java import java.util.Map; import javax.ejb.Local;

@Local public interface EmployeeServiceLocal {

 public void doAction();

}

File: EmployeeServiceRemote.java

import javax.ejb.Remote; @Remote public interface EmployeeServiceRemote {

 public void doAction();

}

File: AnotherBean.java import javax.ejb.Stateless; @Stateless public class AnotherBean implements AnotherBeanLocal {

 public void doAnother(){
   System.out.println("from another bean");
 }

}

File: Main.java import javax.ejb.EJB; import javax.naming.InitialContext; public class Main {

 public static void main(String[] a) throws Exception {
   EmployeeServiceRemote service = null;
   // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
   // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
   service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeBean/remote");
   service.doAction();
 }

}

File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099


      </source>
   
  
 
  



Stateless Session Bean With Three Methods

   <source lang="java">

File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099

File: Main.java import javax.naming.InitialContext; import bean.CountRemote; public class Main {

 public static void main(String[] a) throws Exception {
   String name = "jexp";
   CountRemote service = null;
   // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
   // service = (HelloService)new
   // InitialContext().lookup("java:comp/env/ejb/HelloService");
   service = (CountRemote) new InitialContext().lookup("CountBean/remote");
   int countVal = 9;
   service.set(countVal);
   countVal = service.count();
   System.out.println(countVal);
   System.out.println("Calling count() on beans...");
   countVal = service.count();
   System.out.println(countVal);
   service.remove();
 }

}

File: CountBean.java package bean; import javax.ejb.Remote; import javax.ejb.Remove; import javax.ejb.Stateless; import javax.interceptor.Interceptors; @Stateless @Remote(CountRemote.class) public class CountBean implements CountLocal, CountRemote {

   /** The current counter is our conversational state. */
   private int val;
   /**
    * The count() business method.
    */
   public int count() {
       System.out.println("count()");
       return ++val;
   }
   /**
    * The set() business method.
    */
   public void set(int val) {
       this.val = val;
       System.out.println("set()");
   }
   /**
    * The remove method is annotated so that the container knows
    * it can remove the bean after this method returns.
    */
   @Remove
   public void remove() {
       System.out.println("remove()");
   }

}

File: CountLocal.java package bean;

import javax.ejb.Local; @Local public interface CountLocal {

   /**
    * Increments the counter by 1
    */
   public int count();
   /**
    * Sets the counter to val
    * @param val
    */
   public void set(int val);
   /**
    * removes the counter
    */
   public void remove();
 }

File: CountRemote.java package bean;

import javax.ejb.Remote; @Remote public interface CountRemote{

 /**
  * Increments the counter by 1
  */
 public int count();
 /**
  * Sets the counter to val
  * @param val
  */
 public void set(int val);
 /**
  * removes the counter
  */
 public void remove();

}


      </source>
   
  
 
  



Throw Exception Out of Ejb Method

   <source lang="java">

File: Employee.java import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {

 private int id;
 private String firstName;
 private String lastName;
 @Id
 @GeneratedValue
 public int getId() {
   return id;
 }
 @PostRemove
 public void postRemove()
 {
    System.out.println("@PostRemove");
 }
 public void setId(int id) {
   this.id = id;
 }
 public String getFirstName() {
   return firstName;
 }
 public void setFirstName(String first) {
   this.firstName = first;
 }
 public String getLastName() {
   return lastName;
 }
 public void setLastName(String last) {
   this.lastName = last;
 }

}

File: EmployeeService.java import javax.ejb.Stateless; import javax.transaction.TransactionManager; @Stateless public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {

 public EmployeeService() {
 }
 
 @JndiInjected("java:/TransactionManager")
 TransactionManager tm;
 public void doAction() throws Exception {
   System.out.println("Is there a transaction: " + (tm.getTransaction() != null));
 }

}

File: EmployeeServiceLocal.java

import java.util.Collection; import javax.ejb.Local; @Local public interface EmployeeServiceLocal {

   public void doAction()  throws Exception;

}

File: EmployeeServiceRemote.java


import java.util.Collection; import javax.ejb.Remote; @Remote public interface EmployeeServiceRemote{

 public void doAction()  throws Exception;  

}

File: JndiInjected.java

import java.lang.annotation.*; @Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface JndiInjected {

  String value();

}

File: JndiInjector.java

import java.lang.reflect.*; import javax.ejb.*; import javax.interceptor.*; import javax.naming.*; import javax.annotation.PostConstruct; public class JndiInjector {

  @PostConstruct
  public void jndiInject(InvocationContext invocation) {
     Object target = invocation.getTarget();
     Field[] fields = target.getClass().getDeclaredFields();
     Method[] methods = target.getClass().getDeclaredMethods();
     // find all @JndiInjected fields methods and set them
     try {
        InitialContext ctx = new InitialContext();
        for (Method method : methods) {
           JndiInjected inject = method.getAnnotation(JndiInjected.class);
           if (inject != null) {
              Object obj = ctx.lookup(inject.value());
              method.setAccessible(true);
              method.invoke(target, obj);
           }
        }
        for (Field field : fields) {
           JndiInjected inject = field.getAnnotation(JndiInjected.class);
           if (inject != null) {
              Object obj = ctx.lookup(inject.value());
              field.setAccessible(true);
              field.set(target, obj);
           }
        }
        invocation.proceed();
     } catch (Exception ex) {
        throw new EJBException("Failed to execute @JndiInjected", ex);
     }
  }

}

File: Main.java import java.util.Date; import javax.naming.InitialContext;

public class Main {

 public static void main(String[] a) throws Exception {
   EmployeeServiceRemote service = null;
   // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
   // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
   service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeService/remote");
   
   


   service.doAction();
 }

}

File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099


      </source>
   
  
 
  



Use EJB To Mark EJB

   <source lang="java">

File: Employee.java import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {

 private int id;
 private String firstName;
 private String lastName;
 @Id
 @GeneratedValue
 public int getId() {
   return id;
 }
 @PostRemove
 public void postRemove()
 {
    System.out.println("@PostRemove");
 }
 public void setId(int id) {
   this.id = id;
 }
 public String getFirstName() {
   return firstName;
 }
 public void setFirstName(String first) {
   this.firstName = first;
 }
 public String getLastName() {
   return lastName;
 }
 public void setLastName(String last) {
   this.lastName = last;
 }

}

File: EmployeeService.java import javax.ejb.EJB; import javax.ejb.Stateless; @Stateless public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {

 public EmployeeService() {
 }
 @EJB private EmployeeServiceLocal processPayment;
 
 
 public void doAction() {
   System.out.println("do Action");
   
   processPayment.doAnother();
 }
 public void doAnother() {
   System.out.println("do another");
   
   
 }

}

File: EmployeeServiceLocal.java

import java.util.Collection; import javax.ejb.Local; @Local public interface EmployeeServiceLocal {

   public void doAction();
   public void doAnother();

}

File: EmployeeServiceRemote.java


import java.util.Collection; import javax.ejb.Remote; @Remote public interface EmployeeServiceRemote{

 public void doAction();  
 public void doAnother();

}

File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099

File: Main.java import java.util.Date; import javax.naming.InitialContext;

public class Main {

 public static void main(String[] a) throws Exception {
   EmployeeServiceRemote service = null;
   // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
   // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
   service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeService/remote");
   
   


   service.doAction();
 }

}


      </source>
   
  
 
  



Use Stateless Annotation To Change Ejb Name

   <source lang="java">

File: EmployeeBean.java import javax.ejb.Stateful; import javax.interceptor.AroundInvoke; import javax.interceptor.InvocationContext; @Stateful(name = "MyEmployeeBean") public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote {

 public EmployeeBean() {
 }
 public void doAction() {
   System.out.println("Processing...");
 }
 @AroundInvoke
 public Object TimerLog(InvocationContext ctx) throws Exception {
   String beanClassName = ctx.getClass().getName();
   String businessMethodName = ctx.getMethod().getName();
   String target = beanClassName + "." + businessMethodName;
   long startTime = System.currentTimeMillis();
   System.out.println("Invoking " + target);
   try {
     return ctx.proceed();
   } finally {
     System.out.println("Exiting " + target);
     long totalTime = System.currentTimeMillis() - startTime;
     System.out.println("Business method " + businessMethodName + "in " + beanClassName + "takes "
         + totalTime + "ms to execute");
   }
 }

}

File: EmployeeServiceLocal.java import javax.ejb.Local; import javax.ejb.Remote;

@Local public interface EmployeeServiceLocal{

 public void doAction();

}

File: EmployeeServiceRemote.java import javax.ejb.Remote; @Remote public interface EmployeeServiceRemote {

 public void doAction();

}

File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099

File: Main.java import javax.ejb.EJB; import javax.naming.InitialContext; public class Main {

 public static void main(String[] a) throws Exception {
   EmployeeServiceRemote service = null;
   // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
   // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
   service = (EmployeeServiceRemote) new InitialContext().lookup("MyEmployeeBean/remote");
   service.doAction();
 }

}

File: Employee.java import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.PostRemove; @Entity public class Employee implements java.io.Serializable {

 private int id;
 private String firstName;
 private String lastName;
 @Id
 @GeneratedValue
 public int getId() {
   return id;
 }
 @PostRemove
 public void postRemove()
 {
    System.out.println("@PostRemove");
 }
 public void setId(int id) {
   this.id = id;
 }
 public String getFirstName() {
   return firstName;
 }
 public void setFirstName(String first) {
   this.firstName = first;
 }
 public String getLastName() {
   return lastName;
 }
 public void setLastName(String last) {
   this.lastName = last;
 }

}


      </source>
   
  
 
  



Use Stateless Session Bean To PersistEntity

   <source lang="java">

File: Employee.java import static javax.persistence.FetchType.LAZY; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; @Entity //@Table(name="EMP", schema="HR") @Table(name="EMP") public class Employee implements Serializable {

 @Id
 @Column(name = "EMP_ID")
 private int id;
 @Column(name = "COMM")
 private String name;
 @Column(name = "SAL")
 private long salary;
 @Basic(fetch=LAZY)
 @Lob @Column(name="PIC")
 private byte[] picture;
 
 public Employee() {
 }
 public Employee(int id) {
   this.id = id;
 }
 public int getId() {
   return id;
 }
 public void setId(int id) {
   this.id = id;
 }
 public String getName() {
   return name;
 }
 public void setName(String name) {
   this.name = name;
 }
 public long getSalary() {
   return salary;
 }
 public void setSalary(long salary) {
   this.salary = salary;
 }
 public byte[] getPicture() {
   return picture;
 }
 public void setPicture(byte[] picture) {
   this.picture = picture;
 }
 public String toString() {
   return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary();
 }

}

File: EmployeeService.java

import java.util.Collection; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.naming.Context; import javax.naming.InitialContext; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.transaction.UserTransaction; @Stateless public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {

 @PersistenceContext(unitName="EmployeeService")
 EntityManager em;
 
 public EmployeeService() {
 }
 public Employee createEmployee(int id, String name, long salary, byte[] pic) {
   Employee emp = new Employee(id);
   emp.setName(name);
   emp.setSalary(salary);
   emp.setPicture(pic);
   
   em.persist(emp);
   
   
   emp = findEmployee(id);
   System.out.println(emp);
   
   return emp;
 }
 public void removeEmployee(int id) {
   Employee emp = findEmployee(id);
   if (emp != null) {
     em.remove(emp);
   }
 }
 public Employee raiseEmployeeSalary(int id, long raise) {
   Employee emp = em.find(Employee.class, id);
   if (emp != null) {
     emp.setSalary(emp.getSalary() + raise);
   }
   return emp;
 }
 public Employee findEmployee(int id) {
   return em.find(Employee.class, id);
 }
 public Collection<Employee> findAllEmployees() {
   Query query = em.createQuery("SELECT e FROM Employee e");
   return (Collection<Employee>) query.getResultList();
 }
 
 public void doAction(){
   Employee emp = new Employee(1);
   emp.setName("name");
   emp.setSalary(100);
   emp.setPicture("pic".getBytes());
   
   em.persist(emp);
   
   
   emp = findEmployee(1);
   System.out.println(emp);
 }

}


File: EmployeeServiceLocal.java

import javax.ejb.Local; @Local public interface EmployeeServiceLocal {

   public void doAction();
 public Employee createEmployee(int id, String name, long salary, byte[] pic) ;

}

File: EmployeeServiceRemote.java


import javax.ejb.Remote; @Remote public interface EmployeeServiceRemote{

 public Employee createEmployee(int id, String name, long salary, byte[] pic) ;
 
 public void doAction();

}

File: jndi.properties java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099

File: Main.java import javax.naming.InitialContext; public class Main {

 public static void main(String[] a) throws Exception {
   EmployeeServiceRemote service = null;
   // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
   // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
   service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeService/remote");
   service.createEmployee(158, "AAA", 45000, "asdf".getBytes());
   service.doAction();
 }

}


File: persistence.xml <persistence xmlns="http://java.sun.ru/xml/ns/persistence"

            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://java.sun.ru/xml/ns/persistence http://java.sun.ru/xml/ns/persistence/persistence" version="1.0">
 <persistence-unit name="EmployeeService" > 
       <jta-data-source>java:/DefaultDS</jta-data-source>
       <properties>
        <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
       </properties>
   
 </persistence-unit>

</persistence>

File: ejb-jar.xml <?xml version="1.0" encoding="UTF-8"?> <ejb-jar>

  <enterprise-beans>
  </enterprise-beans>

</ejb-jar>


      </source>