本文介绍了播放框架中的JPA和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个多线程服务器.问题是我得到以下错误: play.exceptions.JPAException:JPA上下文未初始化.在应用程序中找到一个或多个带有@ javax.persistence.Entity批注的类时,JPA Entity Manager会自动启动.
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:
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和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!