EJB3.0 与 Hibernate JPA

EJB3.0 with Hibernate JPA

我想使用 Hibernate JPA 为 EJB 创建 POC,正在关注 this article for the same, I am getting connections exception as posted below. I tried following resolution posted on this thread 但仍然无法连接。

我创建了一个专用的休眠 POC,我可以连接,但不能从 EJB - 休眠组合连接。

    22:27:42,258 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] exporting generated schema to database
    22:27:42,258 WARN  [org.jboss.resource.connectionmanager.JBossManagedConnectionPool] Throwable while attempting to get a new connection: null: org.jboss.resource.JBossResourceException: Could not create connection; - nested throwable: (org.jboss.resource.JBossResourceException: Failed to register driver for: com.mysql.jdbc.Driver; - nested throwable: (java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from BaseClassLoader@a1665c{vfs:///C:/Users/[myname]/workspace/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_AS_6.x1481865411227/deploy/EmployeeManagementEJB.jar}))
        at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:261) [:6.1.0.Final]
        at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:215) [:6.1.0.Final]
        at org.jboss.resource.connectionmanager.InternalManagedConnectionPool.createConnectionEventListener(InternalManagedConnectionPool.java:648) [:6.1.0.Final]
        at org.jboss.resource.connectionmanager.InternalManagedConnectionPool.getConnection(InternalManagedConnectionPool.java:272) [:6.1.0.Final]
        at org.jboss.resource.connectionmanager.JBossManagedConnectionPool$BasePool.getConnection(JBossManagedConnectionPool.java:690) [:6.1.0.Final]
        at org.jboss.resource.connectionmanager.BaseConnectionManager2.getManagedConnection(BaseConnectionManager2.java:403) [:6.1.0.Final]
        at org.jboss.resource.connectionmanager.TxConnectionManager.getManagedConnection(TxConnectionManager.java:414) [:6.1.0.Final]
        at org.jboss.resource.connectionmanager.BaseConnectionManager2.allocateConnection(BaseConnectionManager2.java:496) [:6.1.0.Final]
        at org.jboss.resource.connectionmanager.BaseConnectionManager2$ConnectionManagerProxy.allocateConnection(BaseConnectionManager2.java:941) [:6.1.0.Final]
        at 

//deleted few error lines due to space constrain

org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:538) [:6.1.0.Final]
        at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:228) [:6.1.0.Final]
        ... 86 more
    Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from BaseClassLoader@a1665c{vfs:///C:/Users/[myname]/workspace/.metadata/.plugins/org.jboss.ide.eclipse.as.core/JBoss_AS_6.x1481865411227/deploy/EmployeeManagementEJB.jar}
        at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:480) [jboss-classloader.jar:2.2.1.GA]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357) [:1.8.0_77]
        at java.lang.Class.forName0(Native Method) [:1.8.0_77]
        at java.lang.Class.forName(Class.java:348) [:1.8.0_77]
        at org.jboss.resource.adapter.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:523) [:6.1.0.Final]
        ... 87 more

    22:27:42,262 INFO  [org.hibernate.validator.engine.resolver.DefaultTraversableResolver] Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    22:27:42,270 INFO  [org.hibernate.validator.engine.resolver.DefaultTraversableResolver] Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    22:27:42,272 INFO  [org.hibernate.util.NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
    22:27:42,285 INFO  [org.jboss.ejb3.session.SessionSpecContainer] Starting jboss.j2ee:jar=EmployeeManagementEJB.jar,name=ManageEmployeeBean,service=EJB3
    22:27:42,294 INFO  [org.jboss.ejb3.EJBContainer] STARTED EJB: com.jwt.ejb.business.impl.ManageEmployeeBean ejbName: ManageEmployeeBean
    22:27:42,297 INFO  [org.jboss.ejb3.proxy.impl.jndiregistrar.JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

        ManageEmployeeBean/remote - EJB3.x Default Remote Business Interface
        ManageEmployeeBean/remote-com.jwt.ejb.business.impl.ManageEmployeeBeanRemote - EJB3.x Remote Business Interface

以下是我的数据来源

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE datasources
    PUBLIC "-//JBoss//DTD JBOSS JCA Config 1.5//EN"
    "http://www.jboss.org/j2ee/dtd/jboss-ds_1_5.dtd">
<datasources>
   <local-tx-datasource>
      <jndi-name>EmpMngEJBDatasource</jndi-name>
      <use-java-context>true</use-java-context>
      <connection-url>jdbc:mysql://localhost:3306/new_schema</connection-url>
      <driver-class>com.mysql.jdbc.Driver</driver-class>
      <user-name>root</user-name>
      <password>admin</password>
   </local-tx-datasource>    
</datasources>

以下是我的坚持设置

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
       version="2.0">
  <persistence-unit name="EmpMgmtPU" transaction-type="JTA">
    <jta-data-source>java:/EmpMngEJBDatasource</jta-data-source>
           <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
       <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
   </properties>
  </persistence-unit>
</persistence>

以下是我的实体

package com.jwt.ejb.entity;

import java.io.Serializable;
import javax.persistence.*;

@Entity(name="employee")
public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;

    @Column(name = "first_name", length = 50)
    private String firstName;

    @Column(name = "last_name", length = 50)
    private String lastName;

    @Column(name = "email", length = 50)
    private String email;

    //setter getter - trimed due to space constrain
}

以下为托管bean

package com.jwt.ejb.business.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.*;

import com.jwt.ejb.entity.Employee;
@Stateless
public class ManageEmployeeBean implements ManageEmployeeBeanRemote {

    @PersistenceContext(unitName = "EmpMgmtPU")
    private EntityManager entityManager;     

    @Override
    public boolean addEmployee(Employee employee) {
        entityManager.persist(employee);
        return true;
    }

    @Override
    public List<Employee> getEmployees() {
        return entityManager.createQuery("SELECT e FROM employee e").getResultList();
    }

}

以下是我的客户端代码

package com.jwt.ejb.client;

import java.util.List;
import java.util.Properties;

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

import com.jwt.ejb.business.impl.ManageEmployeeBeanRemote;
import com.jwt.ejb.entity.Employee;


public class Client {
    public static void main(String[] args) {
        ManageEmployeeBeanRemote remote = doLookup();

        List<Employee> employees = remote.getEmployees();
        for(Employee emp : employees){
            System.out.println("---");
            System.out.println("getFirstName : "+emp.getFirstName());
            System.out.println("getLastName : "+emp.getLastName());
            System.out.println("getEmail : "+emp.getEmail());
            System.out.println("getId : "+emp.getId());
        }
    }

    private static ManageEmployeeBeanRemote doLookup() {
        Context context = null;
        ManageEmployeeBeanRemote bean = null;
        try {
            context = getInitialContext();
            bean = (ManageEmployeeBeanRemote) context.lookup(LOOKUP_STRING);
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return bean;
    }

    private static final String LOOKUP_STRING = "ManageEmployeeBean/remote";

    private static final String PROVIDER_URL = "jnp://localhost:1099";

    private static final String JNP_INTERFACES = "org.jboss.naming:org.jnp.interfaces";

    private static final String INITIAL_CONTEXT_FACTORY = "org.jnp.interfaces.NamingContextFactory";
    private static Context initialContext;

    public static Context getInitialContext() throws NamingException {
        if (initialContext == null) {
            // Properties extends HashTable
            Properties prop = new Properties();
            prop.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
            prop.put(Context.URL_PKG_PREFIXES, JNP_INTERFACES);
            prop.put(Context.PROVIDER_URL, PROVIDER_URL);
            initialContext = new InitialContext(prop);
        }
        return initialContext;
    }

}

驱动程序 class 必须在 class 路径上可用。最简单的方法是将 .jar 库放在部署目录中。

对于 EAP 6,它是: JBOSS_HOME/standalone/deployments/