TransactionRequiredException:没有用于当前线程的具有实际事务的EntityManager-无法可靠地处理“合并”调用

问题描述 投票:0回答:1

[我们有一些旧的Spring应用程序,其中几乎没有spring-boot注释。我有一种情况,我想使用EntityManager进行合并,但是会抛出“ javax.persistence.TransactionRequiredException:没有可用于当前线程进行实际事务处理的EntityManager-无法可靠地处理“合并”调用”异常。我尝试了其他文章中提供的解决方案,例如在upload()方法级别使用javax.persistent @Trasactional批注,但没有任何效果。这些是我正在使用的类-

ApplicationContextProvider.java

@Service
public class ApplicationContextProvider implements ApplicationContextAware {

  private static ApplicationContext context;

  public static ApplicationContext getApplicationContext() {
    return context;
  }

  @Override
  public void setApplicationContext(ApplicationContext ac) throws BeansException {
    context = ac;
  }
}

MyConfigType.java

@Entity
@Table(name = "config_loaded_table")
public class MyConfigType { 
  @Id
  private int id;

  @Column(name = "file_name")
  private String fileName;  

    // getters and setters
}

ConfigUploader.java(抽象类)-

public abstract class ConfigUploader {
    public abstract String upload() throws Exception;
}

ConfigLoader实现类,其中我正在使用来自entityManager->的合并]

public class MyConfigLoader extends ConfigUploader {

    private int id;
    private String path;

    public MyConfigLoader(int id, String path) {
        this.id= id;
        this.path=path;
    }

    @Override
    public String upload() throws Exception {

        try {
            MyConfigType myConfigType = new MyConfigType();
            myConfigType.setFileName("employee.config");

            // at this line I am getting exception. 
            int id = ApplicationContextProvider.getApplicationContext().getBean(EntityManager.class).merge(myConfigType).getId();
            myConfigType.setId(id);

        }catch (Exception e) {
            // getting javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'merge' call
           log.error(e); 
        }
    }
}

最后,我正在调用ConfigLoader实现的upload()方法的主类-

public class ConfigThread implements Runnable {

    @Override
    public void run() {

        ConfigUploader configLoader = new MyConfigLoader(id,path);
        configLoader.upload(); // calling upload() method here

    }
}

[我们有一些旧的Spring应用程序,其中几乎没有spring-boot注释。我有一种情况,我想使用EntityManager执行合并,但这会抛出“ javax.persistence ....

spring spring-boot entitymanager javax.persistence
1个回答
0
投票

您需要在@Transactional上添加MyConfigLoader.upload()注释。

© www.soinside.com 2019 - 2024. All rights reserved.