如何将实体绑定到特定的持久性单元

Jav*_*tar 8 java hibernate jpa persistence-unit ejb-3.0

在使用struts2 ejb hibernate的Web应用程序中,是否可以告诉应用程序persistence.xml在部署时间内查找或创建特定持久性单元名称的实体,该实体是在文件中写入的?

persistence.xml在jboss节点下有两个持久性单元和一个数据源(包括两个"local-tx-datasource")xml文件.

为了清楚,我的意思是,我试过这个;

@Entity  
@PersistenceContext(unitName="MY JNDI NAME specified in persistence.xml") 
public abstract class Vehicle {
Run Code Online (Sandbox Code Playgroud)

并没有工作..然后尝试了这等等..

@PersistenceContext(name="MY PERSISTENCE UNIT NAME specified in persistence.xml")

@PersistenceUnit(name="MY PERSISTENCE UNIT NAME specified in persistence.xml")
Run Code Online (Sandbox Code Playgroud)

而且我用"UnitName = .."而不是"name = .."尝试了上面这些,但是任何东西都适用于我......

[解决了]

<.exclude-unlisted-classes> true <./ exclude-unlisted-classes>解决了我的问题

Pas*_*ent 9

更新:根据您的评论(这不是我从原始问题中理解的),我认为除了禁用"发现"并在各自的持久性单元中明确列出您的实体之外,您没有任何其他选择:

<?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="MyPu1" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.mycompany.Foo</class>
    ...
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <!-- H2 in memory -->
      <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
      <property name="javax.persistence.jdbc.username" value="APP"/>
      <property name="javax.persistence.jdbc.password" value="APP"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
  </persistence-unit>

  <persistence-unit name="MyPu2" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.mycompany.Bar</class>
    ...
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties>
      <!-- Derby server -->
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
      <property name="javax.persistence.jdbc.user" value="APP"/>
      <property name="javax.persistence.jdbc.password" value="APP"/>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/Pu2;create=true"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
  </persistence-unit>
</persistence>
Run Code Online (Sandbox Code Playgroud)

我不知道实体级别的任何语法允许将其分配给持久性单元.


我不确定我理解你要做什么,但是如果你想为注入的特定持久性单元获得实体管理器,你应该这样做:

@Stateless
public class FooBean implements Foo {
    @PersistenceContext(unitName="MyPu1")
    EntityManager em1;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

如果这不是您想要的,请澄清问题.