java - 在 @PostConstruct 中的 Spring Boot 中使用普通 EntityManager 持久保存 JPA 实体

标签 java spring-boot jpa entitymanager spring-transactions

我有一个最小的 Spring Boot 应用程序,由 3 个类组成:一个实体、一个尝试在 @PostConstruct 中填充数据库的组件和一个应用程序类。没有别的了。

@SpringBootApplication
public class App {
  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }
}

@Component
@Transactional
public class Initializer {
    @Autowired
    EntityManager em;

    @PostConstruct
    public void populate() {
        em.persist(new MyEntity());
    }
}

@Entity
public class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    int id;
}

当我运行应用程序时,我得到一个 javax.persistence.TransactionRequiredException: No EntityManager withactual transaction available for current thread - Canneable process 'persist' call

我不是唯一一个遇到该错误的人,我阅读了很多帖子,但没有找到神奇的解决方案。

如果我 Autowiring EntityMananagerFactory 而是这样做:

EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(new MyEntity());
em.getTransaction().commit();
em.close();

它有效。问题是:是否有一种更简单的方法(将正确的注释放在正确的位置)来获取可以持久化实体的 EntityManager?我有充分的理由不创建存储库(我尝试这样做并且有效)。

最诚挚的问候詹斯

最佳答案

因此,在尝试了很多不同的东西之后,我认为我找到了一个可行的解决方案,其中初始化是在 ApplicationReadyEvent 处理程序中完成的,而不是在 @PostConstruct 方法中完成的:

@Component
public class Initializer {

    @PersistenceContext
    EntityManager em;

    @EventListener(ApplicationReadyEvent.class)
    @Transactional
    public void init() {
        em.persist(new MyEntity());
    }
}

工作示例:https://github.com/djarnis73/spring-boot-db-init-with-jpa-entity-manager

关于java - 在 @PostConstruct 中的 Spring Boot 中使用普通 EntityManager 持久保存 JPA 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56634009/

相关文章:

java - ftp连接超时异常

java - 在库中捆绑 log4j.properties - 糟糕的风格还是什么?

java - 将 Hibernate 工具移动到构建时间

java - JPA 自引用实体

java - 为什么 * 运算符给出了错误的结果而 Math.pow() 是正确的

java - Spring Rest Docs 片段模板被忽略

java - Spring JPA Repository - 在服务器重启时保留数据

java - 在spring boot中 Autowiring 一个bean,它在主java包中为空,但在测试包中可以工作

java - 设置由数据库生成的 JPA 时间戳列?

java - 如何使用字符串值搜索链接队列类