How to initialize JpaTemplate through Constructor with EntityManager.
samwun9988 Jan 9, 2013 8:10 AMHi, with JBOSS 7.1.1 Final and Hibernate 3.5 (for lucuene Search), I created an ejb module with the following Facade object and its interface:
Facade class:
@Stateless(name = "MyisamProductArticleFacade")
@Local(value = MyisamProductArticleFacadeLocal.class)
@Transactional
public class MyisamProductArticleFacade implements MyisamProductArticleFacadeLocal {
private static final Logger logger = Logger.getLogger(MyisamProductArticleFacade.class);
@PersistenceContext(unitName = "ForestSurfPU")
private EntityManager em;
JpaTemplate jpaTemplate;
public MyisamProductArticleFacade() {
}
/**
*
* @param entityManagerFactory
*/
@Autowired
public MyisamProductArticleFacade(EntityManagerFactory entityManagerFactory) {
this.jpaTemplate = new JpaTemplate(entityManagerFactory);
}
protected EntityManager getEntityManager() {
return em;
}
@Override
public List<MyisamProductArticle> search(final String queryString) {
final String[] fields = new String[]{"header", "a_desc"}; // search on these fields
return (List) this.jpaTemplate.execute(new JpaCallback() { // this.jpaTempalte is null.
@Override
public Object doInJpa(EntityManager em) throws PersistenceException {
List<MyisamProductArticle> results = new ArrayList<MyisamProductArticle>();
try {
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
org.apache.lucene.analysis.standard.StandardAnalyzer
standardAnalyzer = new org.apache.lucene.analysis.standard.StandardAnalyzer(Version.LUCENE_35);
MultiFieldQueryParser parser = new MultiFieldQueryParser(Version.LUCENE_35, fields, standardAnalyzer);
org.apache.lucene.search.Query query = parser.parse(queryString);
FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, MyisamProductArticle.class);
results = fullTextQuery.getResultList();
}
catch (Exception e) {
throw new PersistenceException(e);
}
return results;
}
});
}
Facacde interface:
@Local
public interface MyisamProductArticleFacadeLocal {
public List<MyisamProductArticle> search(String queryString);
}
But I ecounted the following exception when executing method search:
Caused by: java.lang.NullPointerException
at ForestSurf.entity.facade.MyisamProductArticleFacade.search(MyisamProductArticleFacade.java:81) [ForestSurf-ejb-1.0.jar:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_07]
But this.jpaTemplate is not being initialised in the constructor, which is still null here.
Is there anyway initilize the Facade object with constructor when the ejb project is loaded or somehow invoke this initialisation?
Any suggestion is very appreciated.
Thanks
Sam