【问题标题】:How to use EJB 3 with persistence unit on a JBoss AS?如何在 JBoss AS 上使用带有持久性单元的 EJB 3?
【发布时间】:2017-04-14 03:49:04
【问题描述】:

我有一个 JBoss AS,在这个服务器上有一个standalone.xml 文件,其中有几个属性,还有我的数据源,所以如何将standalone.xml 文件中的数据源与我想要的持久性单元结合起来添加到 EJB 中?

【问题讨论】:

    标签: jboss ejb persistence.xml persistence-unit


    【解决方案1】:

    只需将 <jta-data-source>java:/ExampleDS</jta-data-source> 添加到 persistence.xml 中,提供您的数据源 jndi-name。

    数据源示例:

    <datasource jndi-name="java:/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
                        <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
                        <driver>h2</driver>
                        <security>
                            <user-name>sa</user-name>
                            <password>sa</password>
                        </security>
                    </datasource>
    

    persistence.xml 引用数据源 ExampleDS 的示例:

    <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="example">
          <jta-data-source>java:/ExampleDS</jta-data-source>
          <properties>
             <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
             <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
          </properties>
       </persistence-unit>
    </persistence>
    

    在您的 EJB3 中注入持久性单元的示例:

    @Stateless
    public class MyEJB {
    
        @PersistenceContext(unitName="example") protected EntityManager entityManager;
    
        public void createEmployee(String fName, String lName) {
            Employee employee  = new Employee();
            employee.setFirstName(fName);
            employee.setLastName(lName);
            entityManager.persist(employee);
        }
    ...
    }
    

    【讨论】:

    • 我应该在我的包中包含 MySQL 驱动程序连接器吗?
    • 最好的方法是在 JBoss AS 中配置一个模块。要做到这一点,只需遵循该指南:access.redhat.com/documentation/en-US/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    相关资源
    最近更新 更多