无法在Weld&中注入entityManager接缝3

时间:2011-12-02 16:14:26

标签: jpa-2.0 cdi jboss-weld jboss7.x seam3

我开始接触Seam 3和Weld。现在我正在努力坚持 - 实体管理器没有被注入。

拳头,我从头开始设置了一个maven项目(未生成)。该项目有两个子模块:

  • model:只包含实体
  • web:包含前端(jsf)和bean(没有EJB)。该模块取决于模型模块。

所以在Web模块中,我在src/main/resources/META-INF中有我的persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
    <!-- Persistence deployment descriptor for dev profile -->
<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="allternative" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:jboss/datasources/allternativeDS</jta-data-source>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.transaction.manager_lookup_class"
                value="org.hibernate.transaction.JBossTransactionManagerLookup" />
            <property name="hibernate.connection.autocommit" value="true" />
        </properties>
    </persistence-unit>

</persistence>

然后我有了ApplicationInitializer类:

@Named
@ApplicationScoped
public class ApplicationInitializer {

    @Produces
    @PersistenceContext(unitName="allternative")
    @Dependent
    EntityManager entityManager;

    @Produces
    @PersistenceUnit(unitName="allternative")
    @Dependent
    EntityManagerFactory entityManagerFactory;

}

类CurrentUser:

@Named("currentUser")
@SessionScoped
public class CurrentUser implements Serializable {

    private boolean isLogin = false;

    @Inject
    private EntityManager entityManager;

    @Inject
    private Logger log;

    private User user;

    public CurrentUser() {
        this.user = null;
    }

    public User getUser() {
        log.info("getting user");
        if(this.user == null) {
            log.info("user is null, getting default from db");
            this.user = entityManager.find(User.class, "thobens"); // <- strange exception here
//          log.info("took user "+user.getUsername());
        }
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

当我调用#{currentUser.user}时,我得到以下奇怪的异常:

16:57:04,768 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http--127.0.0.1-8080-1) Error Rendering View[/index.xhtml]: javax.el.ELException: /index.xhtml: java.lang.RuntimeException: Can't find a deployment unit named allternative at deployment "web.war"
    at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:183) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at org.richfaces.renderkit.RendererBase.renderChildren(RendererBase.java:278) [richfaces-components-ui-4.0.0.Final.jar:]
    at org.richfaces.renderkit.html.PanelRenderer.encodeEnd(PanelRenderer.java:181) [richfaces-components-ui-4.0.0.Final.jar:]
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at com.ocpsoft.pretty.faces.application.PrettyViewHandler.renderView(PrettyViewHandler.java:163) [prettyfaces-jsf2-3.3.0.jar:]
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594) [jboss-jsf-api_2.1_spec-2.0.0.Beta1.jar:2.0.0.Beta1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:67) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:118) [prettyfaces-jsf2-3.3.0.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.jboss.solder.servlet.exception.CatchExceptionFilter.doFilter(CatchExceptionFilter.java:65) [solder-impl-3.1.0.Beta3.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.jboss.solder.servlet.event.ServletEventBridgeFilter.doFilter(ServletEventBridgeFilter.java:72) [solder-impl-3.1.0.Beta3.jar:]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:139) [jboss-as-web-7.0.2.Final.jar:7.0.2.Final]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:388) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.jboss.as.web.NamingValve.invoke(NamingValve.java:57) [jboss-as-web-7.0.2.Final.jar:7.0.2.Final]
    at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:49) [jboss-as-jpa-7.0.2.Final.jar:7.0.2.Final]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:154) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:667) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:952) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at java.lang.Thread.run(Thread.java:619) [:1.6.0_20]
Caused by: java.lang.RuntimeException: Can't find a deployment unit named allternative at deployment "web.war"
    at org.jboss.as.weld.services.bootstrap.WeldJpaInjectionServices.getScopedPUName(WeldJpaInjectionServices.java:94) [jboss-as-weld-7.0.2.Final.jar:7.0.2.Final]
    at org.jboss.as.weld.services.bootstrap.WeldJpaInjectionServices.resolvePersistenceContext(WeldJpaInjectionServices.java:59) [jboss-as-weld-7.0.2.Final.jar:7.0.2.Final]
    at org.jboss.weld.util.Beans.injectEEFields(Beans.java:784) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:181) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:54) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:176) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:142) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:170) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:339) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.context.AbstractContext.get(AbstractContext.java:122) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:693) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.AbstractReceiverBean.getReceiver(AbstractReceiverBean.java:84) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.ProducerField$1.produce(ProducerField.java:134) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:361) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.createUnderlying(EEResourceProducerField.java:170) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField.access$000(EEResourceProducerField.java:54) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.builtin.ee.EEResourceProducerField$EEResourceCallable.call(EEResourceProducerField.java:80) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.builtin.CallableMethodHandler.invoke(CallableMethodHandler.java:50) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:62) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:125) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at org.jboss.weldx.persistence.EntityManager$-1772293428$Proxy$_$$_Weld$Proxy$.find(EntityManager$-1772293428$Proxy$_$$_Weld$Proxy$.java) [weld-core-1.1.2.Final.jar:]
    at com.allternative.web.security.CurrentUser.getUser(CurrentUser.java:42) [classes:]
    at com.allternative.web.security.CurrentUser$Proxy$_$$_WeldClientProxy.getUser(CurrentUser$Proxy$_$$_WeldClientProxy.java) [classes:]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [:1.6.0_20]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [:1.6.0_20]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [:1.6.0_20]
    at java.lang.reflect.Method.invoke(Method.java:597) [:1.6.0_20]
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:302) [jboss-el-api_2.2_spec-1.0.0.Final.jar:1.0.0.Final]
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at org.apache.el.parser.AstValue.getValue(AstValue.java:134) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:187) [jbossweb-7.0.1.Final.jar:7.0.2.Final]
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:55) [weld-core-1.1.2.Final.jar:2011-07-26 15:02]
    at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:224) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at com.sun.faces.facelets.el.ELText$ELTextComposite.writeText(ELText.java:148) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:85) [jsf-impl-2.1.3-b02-jbossorg-2.jar:2.1.3-SNAPSHOT]
    ... 46 more

只要我触摸entityManager,就会发生这种情况。当我使用@PersistenceContext而不是@Inject对其进行注释时,会在部署时发生此错误。

我想这与persistence.xml没有进行处理有关,因为

a)当我致电Persistence.createEntityManagerFactory("allternative").createEntityManager()时,我收到错误消息,说没有这样的持久性单元。

b)我将hibernate.hbm2ddl.auto设置为“更新”(并尝试使用“创建”),但我没有得到任何反馈,表明我的实体是在数据库中创建的(并且正在运行show tables;在mysql上也会产生一个空集)。如果创建了持久性单元,我也没有得到提示。 DataSource可用(并由JBoss部署)并创建数据库。

我的beans.xml是src/main/webapp/WEB-INF/的locatex(仅限于网络模块):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:t="urn:java:org.jboss.seam.persistence.transaction"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee   
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <interceptors>
        <class>org.jboss.seam.faces.context.conversation.ConversationBoundaryInterceptor</class>
        <class>org.jboss.seam.transaction.TransactionInterceptor</class>
    </interceptors>

</beans>

目前我有一个实体(在模型模块中):

@Entity
@Table(name="user")
public class User {

    @Id
    @Length(min=6, max=32)
    private String username;

    @NotNull
    private String firstname;

    @NotNull
    private String lastname;

    @NotNull
    @Length(min=6, max=64)
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String user) {
        this.username = user;
    }

    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 getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public int hashCode() {
        return this.username.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        if(other == null) {
            return false;
        }
        if(!(other instanceof User)) {
            return false;
        }
        User otherUser = (User)other;
        String user = otherUser.getUsername();
        if(user == null || this.username == null) {
            return false;
        }
        return this.username.equals(user);
    }

    @Override
    public String toString() {
        return this.username;
    }
}

我真的不明白为什么这不起作用。有人可以帮帮我吗?

提前致谢,

安德烈亚斯

2 个答案:

答案 0 :(得分:1)

据我所知, ejb 模块中必须存在persistence.xml模型的包装类型为ejb, ?)。在此目录src/main/resources/META-INF中,我还有一个空的beans.xml

我不确定你的@ApplicationScoped ApplicationInitializer。我认为你正在使用这个类来获得注射@EntityManager,但我不知道这是否是推荐的方式(我希望这个答案是)。您可以在 ejb 模块中尝试以下操作,而不是使用类ApplicationInitializer:创建一个类MyRepository以区分多个持久性单元和一个类MyRepositoryProducer @Produce EntityManager

@Qualifier
@Target({ ElementType.TYPE, ElementType.METHOD,
          ElementType.PARAMETER, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyRepository {}

public class MyRepositoryProducer
{
  @SuppressWarnings("unused")
  @Produces
  @MyRepository
  @PersistenceContext
  private EntityManager em;
}

然后你可以在你的EntityManager - Bean中注入你的CurrentUser

@Inject @MyRepository private EntityManager em;

答案 1 :(得分:1)

为了这个,我必须为自己打风,我拼错了persistence.xml的名字......