将实体管理器注入到托管bean中 [英] Injecting entity manager into managed bean

查看:133
本文介绍了将实体管理器注入到托管bean中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用@PersistenceContext(或@PersistenceUnit)将实体管理器(或其工厂)注入到jsf管理的bean中?

It is possible to inject entity manager (or its factory) into jsf managed bean using @PersistenceContext (or @PersistenceUnit)?

我尝试了一下,但是没有,我得到了NullPointerException.

I Tried it but nothing, I obtain a NullPointerException.

推荐答案

是可以的.这是语法.

@PersistenceContext
EntityManager em;

您的项目中需要有一个persistence.xml.顺便说一句:我正在运行Glassfish 3.

You need to have a persistence.xml in your project. Btw: I'm running Glassfish 3.

此后,您可以使用em.createNamedQuery之类的方法.

After this you can then use methods like em.createNamedQuery.

还请记住,注入是在构造函数之后进行的,因此,如果您尝试在构造函数中执行数据库功能,将无法正常工作.您必须将@PostConstruct批注添加到方法中.这可能是您遇到的问题.

Also remember the injection takes place after the constructor so if your trying to do database functions in the constructor this will not work. You will have to add the @PostConstruct annotation to a method. This is probably the problem your having.

这篇关于将实体管理器注入到托管bean中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆