当放入泛型dao时,entitymanager返回null

时间:2010-09-28 06:58:21

标签: seam

我正在使用带有tomcate和icefaces的seam问题是当我在组件bean中注入实体管理器时它运行良好但是如果把它放在泛型DAO中它返回null我的代码是这样的:

这个豆

@Scope(ScopeType.PAGE)
@Name("TestBean")
public class TestBean {
 public void test(ActionEvent actionEvent) {
  Roles entity = new Roles();
  entity.setName("cons");
  RolesDao dao = new RolesDao();
  dao.emPrisit(entity);

 }
}

DAO

public class RolesDao {
 @In
 EntityManager em;

 public void emPrisit(Roles entity) {
  em.persist(entity);
 }

}

component.xml文件

<persistence:entity-manager-factory name="bookingDatabase"/>

<persistence:managed-persistence-context name="em"
                           auto-create="true" 
                entity-manager-factory="#{bookingDatabase}"/>   

的persistence.xml

<persistence-unit name="bookingDatabase"
  transaction-type="RESOURCE_LOCAL">
  <provider>org.hibernate.ejb.HibernatePersistence </provider>
  <jta-data-source>java:comp/env/AP</jta-data-source>
  <properties>
   <property name="transaction.flush_before_completion" value="true" />
   <property name="transaction.factory_class"
    value="org.hibernate.transaction.JDBCTransactionFactory" />

   <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
   <!--
    <property name="hibernate.transaction.manager_lookup_class"
    value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
   -->

  </properties>
 </persistence-unit>

如果我在bean中注入entitymanger而不是dao,那么当我在entitymanger之前添加这个注释时它运行良好第二个问题

@In
 @PersistenceContext(type = PersistenceContextType.EXTENDED)
 EntityManager em;

它给出了这个例外

caused by: java.lang.IllegalArgumentException: @PersistenceContext may only be used on session bean or message driven bean components: TestBean
 at org.jboss.seam.Component.checkPersistenceContextForComponentType(Component.java:901)
 at org.jboss.seam.Component.scanField(Component.java:877)
 at org.jboss.seam.Component.initMembers(Component.java:557)
 at org.jboss.seam.Component.<init>(Component.java:244)
 at org.jboss.seam.Component.<init>(Component.java:205)
 at org.jboss.seam.init.Initialization.addComponent(Initialization.java:1186)
 ... 13 more

2 个答案:

答案 0 :(得分:1)

注射只发生在Beans中,因此你的DAO应该有@Name(“something”),否则Seam不知道如何处理你的类。

@Name("RolesDao")
public class RolesDao {
   @In
   EntityManager em;

   public void emPrisit(Roles entity) {
       em.persist(entity);
   }
}

然后要使用这个课你应该这样做:

@In(value="RolesDao") // value="..." is optional
private RolesDao rolesDao;

org.jboss.seam.Component.getInstance(RolesDao.class)

很抱歉,如果示例代码有一些错误,则没有eclipse尝试它。

希望这有帮助

答案 1 :(得分:1)

@In上不需要@PersistenceContextEntityManager。对其中一个就足够了。