EntityManager对象没有被Glassfish和Spring注入 [英] EntityManager object is not getting injected with Glassfish and Spring

查看:132
本文介绍了EntityManager对象没有被Glassfish和Spring注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试创建一个工作来删除数据库中的所有记录。这项工作与我的web服务一起部署。在web服务中,我可以轻松访问我的EntityManager,迄今为止它没有任何问题。但是,每当我尝试在我的调度程序中访问EntityManager时,它都会给我带来NullPointerException。即使我试图注入一个我创建的服务,并试图访问它的方法。没有数据库相关工作的方法工作正常并返回结果。但是,在里面使用entityManager的方法抛出了同样的异常。

虽然如果我直接使用URL调用服务,并且所有服务都可以正常工作。

  @Service 
public class DeletionJob {

@PersistenceContext(unitName =my_pu )
private EntityManager em;
@Autowired
私有REST restClass;

@Scheduled(fixedDelay = 10000)
public void run(){
boolean flag = false;
System.out.println(restClass.executeWithoutDB());
System.out.println(restClass.executeWithDB());


配置类别:

  @EnableWebMvc 
@Configuration
@EnableScheduling
@ComponentScan({com.jobs。 *})
@ javax.ws.rs.ApplicationPath(webresources)
public class AppConfig extends Application {
@Bean
public DeletionJob myDeletionJob(){
返回新的DeletionJob();

@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
返回viewResolver;
}
@Bean
public REST restClass(){
return new REST();
}
@Override
public Set< Class<?>> getClasses(){
Set< Class<?>> resources = new java.util.HashSet< Class<>>();
addRestResourceClasses(资源);
返回资源;
}


/ **
*不要修改addRestResourceClasses()方法。
*它会自动填入
*项目中定义的所有资源。
*如果需要,注释掉在getClasses()中调用此方法。
* /
private void addRestResourceClasses(Set< Class<>> resources){
resources.add(com.service.REST.class);
//尝试在这里包含删除工作类,但是,运气仍然不变。
// resources.add(com.jobs.DeletionJob.class);
}
}

persistance.xml文件

 <?xml version =1.0encoding =UTF-8standalone =no?> 
< persistence xmlns =http://java.sun.com/xml/ns/persistencexmlns:xsi =http://www.w3.org/2001/XMLSchema-instanceversion = 1.0xsi:schemaLocation =http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd\">
< persistence-unit name =my_putransaction-type =JTA>
< jta-data-source> ds< / jta-data-source>
< exclude-unlisted-classes> false< / exclude-unlisted-classes>
<属性>
< property name =eclipselink.logging.levelvalue =FINE/>
< / properties>
< / persistence-unit>
< /余辉>

我也尝试使用这个PersistenceAnnotationBeanPostProcessor组件。但是在包含spring-orm之后,它甚至开始给我提供BeanInitializationException的注意事项。其次,我不喜欢使用太多的图书馆。所以,想以最简单的方式做这件事。我可以通过查找JNDI来实现,但问题是我想使用Spring或JAVA EE 6调度程序API。



GlassFish Server的版本:4.1 p>

解决方案

@PersistenceContext在这里简单地被忽略。

实体管理器只能在类事务。
使用一个EntityManagerFactory来创建和销毁一个EntityManager。

  @PersistenceUnit(unitName =my_pu )
private EntityManagerFactory entityManagerFactory;

并且在你的方法中使用下面的行来创建EntityManager: -

  EntityManager entityManager = entityManagerFactory.createEntityManager(); 

请参阅此链接: - 在Spring中注入持久化上下文



我觉得你的持久性上下文不是正确地初始化。


I have been trying to create a job to delete all records from database. This job is deployed with my webservice. In webservice I can easily access my EntityManager and it's having no issues so far. But, whenever I try to access EntityManager in my scheduler then it gives me NullPointerException. Even I have tried to inject a service that I have created and tried to access it's method. The method which have no database related work is working fine and returning me result. But, the method which is using entityManager inside is throwing me the same exception.

While if I directly call the service using URL each and everything works fine in service as well.

@Service
public class DeletionJob {

    @PersistenceContext(unitName = "my_pu")
    private EntityManager em;
    @Autowired
    private REST restClass;

    @Scheduled(fixedDelay=10000)
    public void run() {
        boolean flag = false;
        System.out.println(restClass.executeWithoutDB());
        System.out.println(restClass.executeWithDB());
    }
}

Configuration Class:

@EnableWebMvc
@Configuration
@EnableScheduling
@ComponentScan({ "com.jobs.*" })
@javax.ws.rs.ApplicationPath("webresources")
public class AppConfig extends Application {
     @Bean
     public DeletionJob myDeletionJob() {
         return new DeletionJob();
     } 
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver 
                          = new InternalResourceViewResolver();
        return viewResolver;
    }
        @Bean
        public REST restClass(){
            return new REST(); 
        }
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
        addRestResourceClasses(resources);
        return resources;
    }


    /**
     * Do not modify addRestResourceClasses() method.
     * It is automatically populated with
     * all resources defined in the project.
     * If required, comment out calling this method in getClasses().
     */
    private void addRestResourceClasses(Set<Class<?>> resources) {
        resources.add(com.service.REST.class);
        // Tried to include deletionjob class here but, no luck still the same.
    // resources.add(com.jobs.DeletionJob.class);
    }
}

persistance.xml file:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="my_pu" transaction-type="JTA">
    <jta-data-source>ds</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
        <property name="eclipselink.logging.level" value="FINE"/>
    </properties>
  </persistence-unit>
</persistence>

I have also tried to use this PersistenceAnnotationBeanPostProcessor component. But after including spring-orm it has even started giving me excpetion of BeanInitializationException. Secondly, I am not fond of using too many libraries. So, would like to do this thing in a simplest possible way. I could do it by looking up JNDI, but, the problem is that I want to use Spring or JAVA EE 6 scheduler API.

Version of GlassFish Server: 4.1

解决方案

@PersistenceContext is simply getting ignored here.
An entity manager can only be injected in classes running inside a transaction.
Use an EntityManagerFactory to create and destroy an EntityManager.

@PersistenceUnit(unitName = "my_pu")
private EntityManagerFactory entityManagerFactory;

And inside your method use below line to create EntityManager:-

EntityManager entityManager = entityManagerFactory.createEntityManager();

Refer this link:- Injection of Persistence Context in spring

I feel your Persistence Context is not getting initialized properly.

这篇关于EntityManager对象没有被Glassfish和Spring注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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