nullpoInterException在Singleton类中带有PersistenceContext EntityManager。我该如何解决?
简短版本:我有一个单身派类,每次程序执行只能初始化一次。该类的目的是从数据库中获取恒定数据,该数据库位于其表格中。我目前已经设置了这样的类:
public class MyService {
private static final MyService INSTANCE = new MyService();
// Evaluates to null
@PersistenceContext(unitName = "mydb")
private EntityManager myEntityManager;
private int myDbConstant;
private MyEnum myEnum;
public static getInstance() {
return INSTANCE;
}
public int getDbConstant() {
return myDbConstant;
}
public MyEnum getMyEnum() {
return myEnum;
}
private MyService() {
readValues();
}
// This method fetches the constant values from the database
private void readValues() {
List<MyEntity> constantEntities = myEntityManager.createNamedQuery(MyEntity.FIND_ALL).getResultList(); // NullPointerException
// ...
}
}
但是,就像实体管理器试图获取实体一样,这似乎总是会导致nullpointerexception
。我不太确定会导致这一点的原因。我的项目位于EJB容器中,因此我的理解是我不应该自己创建EM。
新的myService();
是否可能是问题?如果是这样,我将如何在维持此类班级的单身性质的同时围绕它进行工作?
Short version: I have a singleton class that should only be initialized once per program execution. The goal of this class is to fetch constant data from the database, which lies in its own table. I've currently got the class set up like this:
public class MyService {
private static final MyService INSTANCE = new MyService();
// Evaluates to null
@PersistenceContext(unitName = "mydb")
private EntityManager myEntityManager;
private int myDbConstant;
private MyEnum myEnum;
public static getInstance() {
return INSTANCE;
}
public int getDbConstant() {
return myDbConstant;
}
public MyEnum getMyEnum() {
return myEnum;
}
private MyService() {
readValues();
}
// This method fetches the constant values from the database
private void readValues() {
List<MyEntity> constantEntities = myEntityManager.createNamedQuery(MyEntity.FIND_ALL).getResultList(); // NullPointerException
// ...
}
}
However, this always seems to result in a NullPointerException
just as the entity manager tries to fetch the entities. I'm not really sure what could be causing this. My project is in an EJB container so my understanding is I'm not supposed to create the EM myself.
Is it possible that the new MyService();
is the problem? If so, how would I work around it while maintaining the singleton nature of this class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
MyService
class注释了@singletone
@singleds> @sing> @Stareless 的适当注释吗?Is your
MyService
class annotated with appropriate annotations like@Singletone
or@Stareless
?