gpt4 book ai didi

java - 如何将 Hibernate 的 Session 注入(inject) micronaut 中的异步监听器?

转载 作者:行者123 更新时间:2023-12-05 07:18:12 36 4
gpt4 key购买 nike

我正在尝试将 Hibernate session 注入(inject)到编程为在工作线程上运行的监听器。

所以我有这种 Activity 。

public class SomeEvent {
public long id;
public Double value;
}

我从服务中推送它。

import javax.inject.Singleton;
import io.micronaut.context.event.ApplicationEventPublisher;

@Singleton
public class SomeService {

public void createAndPublish(Create payload) {
Record record = this.create(payload);
Long id = record.getId();
record.setValue(10);
assert id != null;

SomeEvent event = new SomeEvent();
event.id = id;
event.value = 10;

publisher.publishEvent(event);
}
}

这是我的听众

import javax.persistence.EntityManager;
import javax.inject.Singleton;
import io.micronaut.runtime.event.annotation.EventListener;
import io.micronaut.scheduling.annotation.Async;
import io.micronaut.spring.tx.annotation.Transactional;
import io.micronaut.configuration.hibernate.jpa.scope.CurrentSession;

@Singleton
public class SomeEventListener {

protected EntityManager em;

public SomeEventListener(@CurrentSession EntityManager em) {
this.em = em;
}


@Transactional
@EventListener
@Async
onSomeEvent(SomeEvent event) {
// Do something with event..
}
}

但是 micronaut 无法创建 Hibernate session 。

01:10:05.017 [pool-1-thread-3] ERROR i.micronaut.scheduling.TaskExecutors - Error occurred executing @Async method [void onSomeEvent(SomeEvent event)]: Error instantiating bean of type [org.hibernate.Session]: Could not obtain transaction-synchronized Session for current thread

最佳答案

您可以通过向监听器注入(inject)一个已经注入(inject)了 entitymanager 的服务来解决问题,并完成真正的工作:

    @Singleton
public class DoTheJobService {

protected EntityManager em;

public DoTheJobService(@CurrentSession EntityManager em) {
this.em = em;
}

public void doTheJob(Integer id) {
// Do something with database
}
}

然后从监听器调用:

   @Singleton
public class SomeEventListener {

protected DoTheJobService svc;

public SomeEventListener(DoTheJobService s) {
this.svc = s;
}

@Transactional
@EventListener
@Async
void onSomeEvent(SomeEvent event) {
svc.doTheJob(event.id);
}
}

关于java - 如何将 Hibernate 的 Session 注入(inject) micronaut 中的异步监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58466242/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com