Hi
I was configuring statistics collection via Hibernate JMX for an
JPA-Hibernate application created
http://wiki.netbeans.org/wiki/view/UsingHibernateWithJPA. I created the
following :
* simpleHibernateAppAgent.java
o web-tier JMX Agent with @PersistenceUnit resource injection
which unfortunately was not successful (the injected
EntityManagerFactory emf was found to be null as indicated
in debug results in server.log). simpleHibernateAppAgent is
very similar to other web-tier controller codes with
successful @PersistenceUnit injection.
* ManufacturerController.java
o web-tier controller codes with successful @PersistenceUnit
injection, shown by successful execution of Entity queries
and also debug statements showing emf != null.
* persistence.xml
o included as reference.
[Note: When I modified simpleHibernateAppAgent.getDefault( ) and init( )
to getDefault(emf) and init(emf) and to pass emf as a parameter from
ManufacturerController to simpleHibernateAppAgent.getDefault(emf),
everything seem to work fine. Just seems that @PersistenceUnit injection
in simpleHibernateAppAgent is not working.]
*Question:* Both simpleHibernateappAgent and ManufacturerController are
using same @PersistenceUnit to inject the EntityManagerFactory but why
is injection failed in 1st case while succeeded in 2nd case?
Appreciate any advice.
Thanks
Max
/*
* simpleHibernateAppAgent.java
*
*/
package simpleHibernateApp.agents;
import java.lang.management.ManagementFactory;
import javax.annotation.Resource;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.management.ManagementService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.jmx.StatisticsService;
/**
* JMX agent class.
* You may use the New JMX MBean wizard to create a Managed Bean.
* @author Max.Poon_at_Sun.COM
*/
public class simpleHibernateAppAgent {
@PersistenceUnit(unitName = "SimpleHibernateAppPU")
EntityManagerFactory emf;
private EntityManager em = null;
private Session session = null;
private SessionFactory sf = null;
/**
* Instantiate and register your MBeans.
*/
public void init() throws Exception {
try {
if (emf == null) System.out.println("****** emf null");
em = emf.createEntityManager();
if (em == null) System.out.println("****** em null");
session = (Session) em.getDelegate();
if (session == null) System.out.println("****** session null");
sf = session.getSessionFactory();
if (sf == null) System.out.println("****** sf null");
} catch (Exception ex) {
System.out.println(ex);
} finally {
em.close();
}
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName on = new ObjectName("Hibernate:type=statistics,application=SimpleHibernateApp");
StatisticsService statsMBean = new StatisticsService();
statsMBean.setStatisticsEnabled(true);
statsMBean.setSessionFactory(sf);
mBeanServer.registerMBean(statsMBean, on);
CacheManager cacheMgr = new CacheManager();
ManagementService.registerMBeans(cacheMgr, mBeanServer, true, true, true, true);
}
/**
* Returns an agent singleton.
*/
public synchronized static simpleHibernateAppAgent getDefault() throws Exception {
if(singleton == null) {
singleton = new simpleHibernateAppAgent();
singleton.init();
}
return singleton;
}
public MBeanServer getMBeanServer() {
return mbs;
}
// Platform MBeanServer used to register your MBeans
private final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
// Singleton instance
private static simpleHibernateAppAgent singleton;
}
/*
* ManufacturerController.java
*
*/
package simpleHibernateApp.controller;
import java.util.ArrayList;
import java.util.Collection;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import simpleHibernateApp.agents.simpleHibernateAppAgent;
import simpleHibernateApp.entities.Manufacturer;
/**
*
* @author Max.Poon_at_Sun.COM
*/
public class ManufacturerController {
/** Creates a new instance of ManufacturerController */
public ManufacturerController() { }
private Manufacturer manufacturer;
private DataModel model;
@Resource
private UserTransaction utx;
@PersistenceUnit(unitName = "SimpleHibernateAppPU")
private EntityManagerFactory emf;
private EntityManager getEntityManager() {
initJMX();
return emf.createEntityManager();
}
// Initiate JMX Agent if needed
void initJMX() {
try {
simpleHibernateAppAgent.getDefault();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private int batchSize = 20;
private int firstItem = 0;
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
}
public DataModel getDetailManufacturers() {
return model;
}
public void setDetailManufacturers(Collection<Manufacturer> m) {
model = new ListDataModel(new ArrayList(m));
}
public String createSetup() {
this.manufacturer = new Manufacturer();
return "manufacturer_create";
}
public String create() {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
em.persist(manufacturer);
utx.commit();
addSuccessMessage("Manufacturer was successfully created.");
} catch (Exception ex) {
try {
addErrorMessage(ex.getLocalizedMessage());
utx.rollback();
} catch (Exception e) {
addErrorMessage(e.getLocalizedMessage());
}
} finally {
em.close();
}
return "manufacturer_list";
}
public String detailSetup() {
setManufacturerFromRequestParam();
return "manufacturer_detail";
}
public String editSetup() {
setManufacturerFromRequestParam();
return "manufacturer_edit";
}
public String edit() {
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
manufacturer = em.merge(manufacturer);
utx.commit();
addSuccessMessage("Manufacturer was successfully updated.");
} catch (Exception ex) {
try {
addErrorMessage(ex.getLocalizedMessage());
utx.rollback();
} catch (Exception e) {
addErrorMessage(e.getLocalizedMessage());
}
} finally {
em.close();
}
return "manufacturer_list";
}
public String destroy() {
EntityManager em = null;
try {
utx.begin();
Manufacturer manufacturer = getManufacturerFromRequestParam();
em = getEntityManager();
manufacturer = em.merge(manufacturer);
em.remove(manufacturer);
utx.commit();
addSuccessMessage("Manufacturer was successfully deleted.");
} catch (Exception ex) {
try {
addErrorMessage(ex.getLocalizedMessage());
utx.rollback();
} catch (Exception e) {
addErrorMessage(e.getLocalizedMessage());
}
} finally {
em.close();
}
return "manufacturer_list";
}
public Manufacturer getManufacturerFromRequestParam() {
EntityManager em = getEntityManager();
try{
Manufacturer o = (Manufacturer) model.getRowData();
o = em.merge(o);
return o;
} finally {
em.close();
}
}
public void setManufacturerFromRequestParam() {
Manufacturer manufacturer = getManufacturerFromRequestParam();
setManufacturer(manufacturer);
}
public DataModel getManufacturers() {
EntityManager em = getEntityManager();
try{
Query q = em.createQuery("select object(o) from Manufacturer as o");
q.setMaxResults(batchSize);
q.setFirstResult(firstItem);
model = new ListDataModel(q.getResultList());
return model;
} finally {
em.close();
}
}
public static void addErrorMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, facesMsg);
}
public static void addSuccessMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage("successInfo", facesMsg);
}
public Manufacturer findManufacturer(Integer id) {
EntityManager em = getEntityManager();
try{
Manufacturer o = (Manufacturer) em.find(Manufacturer.class, id);
return o;
} finally {
em.close();
}
}
public int getItemCount() {
EntityManager em = getEntityManager();
try{
int count = ((Long) em.createQuery("select count(o) from Manufacturer as o").getSingleResult()).intValue();
return count;
} finally {
em.close();
}
}
public int getFirstItem() {
return firstItem;
}
public int getLastItem() {
int size = getItemCount();
return firstItem + batchSize > size ? size : firstItem + batchSize;
}
public int getBatchSize() {
return batchSize;
}
public String next() {
if (firstItem + batchSize < getItemCount()) {
firstItem += batchSize;
}
return "manufacturer_list";
}
public String prev() {
firstItem -= batchSize;
if (firstItem < 0) {
firstItem = 0;
}
return "manufacturer_list";
}
}