JPA 和 Threads in play 框架 [英] JPA and Threads in play framework

查看:22
本文介绍了JPA 和 Threads in play 框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个多线程服务器.问题是我收到以下错误:play.exceptions.JPAException:JPA 上下文未初始化.当在应用程序中找到一个或多个使用 @javax.persistence.Entity 注释的类时,JPA 实体管理器会自动启动.

I'm trying to create a multithreading server. The problem is that I get the following error: play.exceptions.JPAException: The JPA context is not initialized. JPA Entity Manager automatically start when one or more classes annotated with the @javax.persistence.Entity annotation are found in the application.

我想要做的是从新线程访问数据库,这是代码

What I'm trying to do is access the db from the new thread here's the code

package controllers;
import java.util.Iterator;
import java.util.List;
import models.Ball;


public class MainLoop extends Thread {

@Override
public void run() {
    List<Ball> balls;
    new Ball(5,5,2,2,10,15);
    while (true){
        balls = Ball.all().fetch(); //Here throws an exception 

        for (Iterator iterator = balls.iterator(); iterator.hasNext();) {
            Ball ball = (Ball) iterator.next();
            ball.applyForces();
        }
    }
}
}

有什么想法吗?

推荐答案

不要使用普通线程,而是使用作业:

Don't use plain thread, use jobs instead :

@OnApplicationStart 
public class MainLoop extends Job { 
       public void doJob() { 
               new BallJob().now(); 
       }
} 

和 BallJob :

And BallJob :

public class BallJob extends Job {
public void doJob() {
    List<Ball> balls;
    new Ball(5,5,2,2,10,15);
    while (true){
        balls = Ball.all().fetch(); 
        for (Iterator iterator = balls.iterator(); iterator.hasNext();) {
            Ball ball = (Ball) iterator.next();
            ball.applyForces();
        }
    }
}

这篇关于JPA 和 Threads in play 框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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