[英]Make a DAO injection in a thread
I am developing a web application in java ee with wildfly, I have to develop a web service that responds immediately to the client, but you have to create a task or a thread to perform some tasks and finally update a record in the database我正在用wildfly在java ee中开发一个Web应用程序,我必须开发一个立即响应客户端的Web服务,但是您必须创建一个任务或一个线程来执行一些任务并最终更新数据库中的记录
This is a basic example, here the thread is created这是一个基本的例子,这里创建了线程
@GET
@Path("/createReq")
@Produces("application/json")
public void createReq() {
objThread trip = new ObjThread();
trip.setIdTrip("id");
trip.start();
}
This is a basic example, here the thread is created这是一个基本的例子,这里创建了线程
public class ObjThread extends Thread {
volatile boolean ejecutar = true;
public String idTrip;
private int time = 0;
@Inject
Tbl_car_tripDAO tripDAO;
@Override
public void run() {
try {
while (ejecutar) {
if (time == 1) {
// task 1
} else if (time == 3) { //30
// task 2
} else if (time >= 5) { //45
// task 3
detener();
changeStatus();
}
Thread.sleep(1000);
time++;
}
} catch (Exception e) {
// TODO: handle exception
}
}
public void detener() {
ejecutar = false;
}
public void changeStatus() {
try {
Tbl_car_trip trip= tripDAO.getTripByIdTrip(idTrip);
trip.setCar_tri_status("data");
tripDAO.update(trip);
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
public void setIdTrip(String idTrip) {
this.idTrip = idTrip;
}
}
But at the time of execution I get a persistence error in the changeStatus method, but if I use the same method with the @inject annotation in another class, it works correctly.Could you please help me with this problem with a recommendation.但是在执行时,我在 changeStatus 方法中遇到了持久性错误,但是如果我在另一个类中使用带有 @inject 批注的相同方法,它可以正常工作。请您帮我解决这个问题并提出建议。 Thank you
谢谢
Updagrade升级
This is my DAO class这是我的 DAO 课程
@Singleton
public class Tbl_car_tripDAO {
@Inject
private EntityManager em;
public boolean update(Tbl_car_trip tbl_car_trip) {
try {
em.merge(tbl_car_trip);
return true;
} catch (Exception e) {
return false;
}
}
the ObjThread must be a Spring bean so you can inject the dependency (Tbl_car_tripDAO). ObjThread 必须是 Spring bean,以便您可以注入依赖项 (Tbl_car_tripDAO)。
@Component
@Scope("prototype")
public class ObjThread extends Thread {
You will need to obtain the ObjThread from the Sprint context (cannot instantiate with new ObjThread ()您将需要从 Sprint 上下文中获取 ObjThread(无法使用 new ObjThread() 进行实例化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.