mai

11

EJB3 /spring and Jboss 4

Posted by : admin | On : 11 mai 2012

This tutorial is inspired from (run under glassfish)

http://java.dzone.com/articles/ejb-30-and-spring-25

In this following page I modified the spring configuration and test the deployment on Jboss 4.2
Environnement tool requirement
- Spring Tools suite or Eclipse
- Jboss 4.2.x (tested on version jboss-4.2.3.GA)
- Spring 2.5.6

The data layer is using @Entity to define the Table (or pojo) that will correspond to our data model
Here we have a simple table called Customer with a series of fields
then we need to ask ourself which services do we want to expose to others ?
As in Facade design pattern we will expose an interface and the method that the client can attack on the server side
So here we define an interface call CustomerService that is annoted with @Remote
Then we’ve implement the CRUD operation and @PersistenceContext in  CustomerServiceImpl class

Then in the second part of the tutorial we are viewing how to bind Spring with EJB 3
To do that you’ll need to investigate the name of jndi register in your server.
The tag jee:jndi-lookup will bind both EJB context  and spring context
Once your project is set up you can easily use Spring test or more simply define a Java project that reference your Ejb project (write a main )

 

 

Go further

http://what-when-how.com/enterprise-javabeans-3/combining-the-power-of-ejb-3-and-spring/

 

Project look like

 

 

 

Setup Jboss

 

 

When you start your server you should have the following log

17:30:56,041 INFO  [SessionFactoryObjectFactory] Factory name: persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,041 INFO  [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
17:30:56,041 INFO  [SessionFactoryObjectFactory] Bound factory to JNDI name: persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,041 WARN  [SessionFactoryObjectFactory] InitialContext did not implement EventContext
17:30:56,041 INFO  [SchemaUpdate] Running hbm2ddl schema update
17:30:56,041 INFO  [SchemaUpdate] fetching database metadata
17:30:56,041 INFO  [SchemaUpdate] updating schema
17:30:56,072 INFO  [TableMetadata] table found: PUBLIC.CUSTOMER
17:30:56,072 INFO  [TableMetadata] columns: [first_name, middle_name, last_name, email_id, customer_id]
17:30:56,072 INFO  [TableMetadata] foreign keys: []
17:30:56,072 INFO  [TableMetadata] indexes: [sys_idx_60]
17:30:56,072 INFO  [SchemaUpdate] schema update complete
17:30:56,072 INFO  [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
17:30:56,150 INFO  [JmxKernelAbstraction] creating wrapper delegate for: org.jboss.ejb3.stateless.StatelessContainer
17:30:56,150 INFO  [JmxKernelAbstraction] installing MBean: jboss.j2ee:jar=CustomerService.jar,name=CustomerServiceImpl,service=EJB3 with dependencies:
17:30:56,150 INFO  [JmxKernelAbstraction]     persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,182 INFO  [EJBContainer] STARTED EJB: com.ejb.service.CustomerServiceImpl ejbName: CustomerServiceImpl
17:30:56,213 INFO  [EJB3Deployer] Deployed: file:/C:/jboss-4.2.3.GA-jdk6/jboss-4.2.3.GA/server/default/deploy/CustomerService.jar
17:30:56,229 INFO  [DefaultEndpointRegistry] register: jboss.ws:context=CustomerService,endpoint=CustomerServiceImpl
17:30:56,338 INFO  [TomcatDeployer] deploy, ctxPath=/CustomerService, warUrl=…/tmp/deploy/CustomerService.jar38776.war/
17:30:57,432 INFO  [WSDLFilePublisher] WSDL published to: file:/C:/jboss-4.2.3.GA-jdk6/jboss-4.2.3.GA/server/default/data/wsdl/CustomerService.jar/CustomerService38777.wsdl
17:30:57,744 INFO  [TomcatDeployer] deploy, ctxPath=/jmx-console, warUrl=…/deploy/jmx-console.war/
17:30:57,885 INFO  [Http11Protocol] Démarrage de Coyote HTTP/1.1 sur http-127.0.0.1-8080

 

Compy spring.jar in the path

<Jboss_HOME>\server\default\lib

 

check the deployement of webservices

http://127.0.0.1:8080/CustomerService/CustomerServiceImpl?wsdl

 

 

Jmx console

 

 

 

check the deployement of EJB3

 

Check the JNDI view deployment you should view

 

 

 

Mbean database=localDB,service=Hypersonic call the Mbean Hypersonic and click start

 

 

package com.ejb.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
//@Table(name = "CUSTOMER", catalog = "", schema = "ADMIN")
public class Customer implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "CUSTOMER_ID")
    private Long customerId;
    @Column(name = "FIRST_NAME")
    private String firstName;
    @Column(name = "LAST_NAME")
    private String lastName;
    @Column(name = "MIDDLE_NAME")
    private String middleName;
    @Column(name = "EMAIL_ID")
    private String emailId;

    public Customer() {
    }

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

    public Long getCustomerId() {
        return customerId;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

}

package com.ejb.service;

import java.util.Collection;

import javax.ejb.Remote;

import com.ejb.domain.Customer;

@Remote
public interface CustomerService {

    Customer create(Customer info);

    Customer update(Customer info);

    void remove(Long customerId);

    Collection<Customer> findAll();

    Customer[] findAllAsArray();

    Customer findByPrimaryKey(Long customerId);
}

package com.ejb.service;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.ejb.domain.Customer;

@WebService(name = "CustomerService", serviceName = "CustomerService", targetNamespace = "urn:CustomerService")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@Stateless(name = "CustomerServiceImpl")
public class CustomerServiceImpl implements CustomerService {

    @PersistenceContext(name="Customer")
    private EntityManager manager;

    @WebMethod
    public Customer create(Customer info) {
        this.manager.persist(info);
        return info;
    }

    @WebMethod
    public Customer update(Customer info) {
        return this.manager.merge(info);
    }

    @WebMethod
    public void remove(Long customerId) {
        this.manager.remove(this.manager.getReference(Customer.class, customerId));
    }

    public Collection<Customer> findAll() {
        Query query = this.manager.createQuery("SELECT c FROM Customer c");
        return query.getResultList();
    }

    @WebMethod
    public Customer[] findAllAsArray() {
        Collection<Customer> collection = findAll();
        return (Customer[]) collection.toArray(new Customer[collection.size()]);
    }

    @WebMethod
    public Customer findByPrimaryKey(Long customerId) {
        return (Customer) this.manager.find(Customer.class, customerId);
    }

}

package com.spring.service;

import com.ejb.domain.Customer;

public interface CustomerManager {
    public void addCustomer(Customer customer);
    public void removeCustomer(Long customerId);
    public Customer[] listCustomers();
}

package com.spring.service;

import com.ejb.domain.Customer;
import com.ejb.service.CustomerService;

public class CustomerManagerImpl implements CustomerManager {

    CustomerService customerService;

    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }

    public void removeCustomer(Long customerId) {
        customerService.remove(customerId);
    }

    public Customer[] listCustomers() {
        return customerService.findAllAsArray();
    }

    public void addCustomer(Customer customer) {
        customerService.create(customer);
    }
}

Persistence Unit

in HSQL embein Jboss the configuration will be

<persistence>
   <persistence-unit name="Customer">
   	 <class>com.ejb.domain.Customer</class>
      <jta-data-source>java:/DefaultDS</jta-data-source>
      <properties>
      	 <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
      </properties>
   </persistence-unit>
</persistence>

in MySQL the configuration will be

<properties>

			<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
			<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" />
			<property name="javax.persistence.jdbc.user" value="root" />
			<property name="javax.persistence.jdbc.password" value="" />
			<!-- EclipseLink should create the database schema automatically -->
			<property name="eclipselink.ddl-generation" value="create-tables" />
			<property name="eclipselink.ddl-generation.output-mode"
				value="database" />
		</properties>

 

 

the Spring configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
       http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">

	<!-- Use a custom JNDI bean factory configured not to prepend lookups with
		"java:comp/env" -->
	<bean id="jndiFactory" class="org.springframework.jndi.support.SimpleJndiBeanFactory">
		<property name="resourceRef" value="false" />
	</bean>

	<!-- Configure the CommonAnnotationBeanPostProcessor to always use JNDI
		lookup (for EJBs) and use the custom JNDI bean factory above. -->
	<bean
		class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
		<property name="alwaysUseJndiLookup" value="true" />
		<property name="jndiFactory" ref="jndiFactory" />
	</bean>

	<!-- <jee:jndi-lookup id="customerService"
		jndi-name="com.ejb.service.CustomerServiceImpl">
	</jee:jndi-lookup> -->

	<jee:jndi-lookup id="customerService" jndi-name="CustomerServiceImpl/remote"
		lookup-on-startup="false" proxy-interface="com.ejb.service.CustomerService"></jee:jndi-lookup>

	<bean id="manageCustomer" class="com.spring.service.CustomerManagerImpl">
		<property name="customerService" ref="customerService" />
	</bean>
</beans>

 

The client test configuration project

 

you’re project should like like this

 

*in the classpath create a jndi.propertiesand java  class client

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
package com.spring.client;

import javax.naming.Context;
import javax.naming.InitialContext;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ejb.domain.Customer;
import com.ejb.service.CustomerService;
import com.spring.service.CustomerManager;

public class SpringAndEJBMain {

    public static void main(String[] args) {

        try {
            Context context = new InitialContext();
            CustomerService stock = (CustomerService) context.lookup("CustomerService/remote");

             ApplicationContext contextSpring =new ClassPathXmlApplicationContext("SpringXMLConfig.xml");

             CustomerManager service = (CustomerManager) contextSpring.getBean("manageCustomer");
             Customer customer = new Customer();
             customer.setFirstName("Meera");
             customer.setLastName("Subbarao");
             customer.setMiddleName("B");
             customer.setEmailId("meera@springandejb.com");
             customer.setCustomerId(new Long(1));

             service.addCustomer(customer);
             for (Customer cust : service.listCustomers()) {
                 System.out.println(cust.getFirstName());
                 System.out.println(cust.getLastName());
                 System.out.println(cust.getMiddleName());
                 System.out.println(cust.getEmailId());

             }
            // service.removeCustomer(new Long(1));

        }
        catch (Exception e) {
	         e.printStackTrace();
	      }

    }
}

Laisser un commentaire

Your email address will not be published. Required fields are marked *