This content has been marked as final.
Show 1 reply
-
1. Re: weld+jpa+tomcat
ssamayoagt Dec 5, 2010 5:49 PM (in response to hengheng)Tomcat isnt JEE app server is just servlet + jsp container.
I use JSF 2 + RichFaces 3.3.3 + Weld 1.0.1 + Hibernate 3.6 (JPA2) in Tomcat 7.
First of all, you cant inject PersistenceContext into your beans nor use extended persistence context, you can only use resource local transactions and non jta connections.
In my applications I have an application scoped named bean wich produces the PesistenceContextFactory, for example:
@Named
@ApplicationScoped
public class Application {
private EntityManagerFactory entityManagerFactory;
@Produces
public EntityManagerFactory getEntityManagerFactory() {
if (entityManagerFactory == null) {
entityManagerFactory = Persistence
.createEntityManagerFactory("demo");
}
return entityManagerFactory;
}
}
So in my JSF backing beans I get an EntityManager from the factory each time I need, for example (actual code):
public class JPAEntityPageBean<E> extends PageBean {
...
@Inject
protected EntityManagerFactory emf;
...
protected EntityManager createEntityManager() {
return emf.createEntityManager();
}
...
protected String getListQL() {
if (listQL == null) {
listQL = "select e from " + getEntityClass().getSimpleName() + " e";
}
return listQL;
}
...
@SuppressWarnings("unchecked")
public List<E> getList() {
if (entityList == null) {
em = createEntityManager();
try {
entityList = getListQuery().getResultList();
} finally {
em.close();
}
}
return entityList;
}
...
// Part of the code borrowed from Seam...
@SuppressWarnings("unchecked")
public Class<E> getEntityClass() {
if (entityClass == null) {
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType) type;
entityClass = (Class<E>) paramType.getActualTypeArguments()[0];
} else {
throw new IllegalArgumentException(
"Could not guess entity class by reflection");
}
}
return entityClass;
}
So, each time I need an EntityManager/persistence context I need to create it.
I have to take all precautions when merging data since basically I use detached entities.
BTW as I wrote more code I was basically replicating (reiventing) Seam's 2.x Query and EntityHome code but much simpler and focused on JPA in a non JEE environment.
Hope this helps you.
Regards.