【发布时间】:2016-09-01 17:05:00
【问题描述】:
我正在开发一个 Java EE 7 maven 项目,我正在使用 Wildfly 8.2,一切都很好,问题是当我使用托管 bean(支持 bean)中的 @PersistenceContext 创建一个实体管理器时,我与我的 jsf 一起使用容器创建一个实体管理器对象,它可以工作,但是当我尝试在我的 DAO 层中使用实体管理器时,它不起作用,它们保持为空值,我不知道为什么我的 dao 层中的代码可以帮助我? .
dao接口:
public interface ICategoryDao {
Category addCategory(Category category);
void deleteCategory(Long codeCategory);
Set<Category> getAllCategories();
Category updateCategory(Category category);
}
dao 实现:
@Named("categoryDao")
public class CategoryDao implements ICategoryDao{
private Logger log = Logger.getLogger(CategoryDao.class);
@PersistenceContext(unitName="BooksStore")
private EntityManager em ;
@Override
public Category addCategory(Category category) {
if(em==null)
{
log.info("em is null ");
return category;
}
em.getTransaction().begin();
em.persist(category);
em.getTransaction().commit();
log.info("CategoryDao : Object persisted." );
return category;
}
@Override
public void deleteCategory(Long codeCategory) {
// TODO Auto-generated method stub
}
@Override
public Set<Category> getAllCategories() {
// TODO Auto-generated method stub
return null;
}
@Override
public Category updateCategory(Category category) {
// TODO Auto-generated method stub
return null;
}
}
这是我的 beans.xml
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">
</beans>
我的 persistance.xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="BooksStore" transaction-type="JTA">
<jta-data-source>java:/bookstore</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
【问题讨论】:
-
你有一个使用
ICategoryDao的例子吗? -
谢谢它现在可以工作了,只是我添加了这两个 EJB 注释:“@Singleton”“@TransactionManagement(TransactionManagementType.CONTAINER)
-
@ErrabiAyoub,因为您自己找到了答案,您应该将其作为答案发布并接受。
标签: jpa jakarta-ee cdi ejb-3.0 wildfly-8