我正在尝试创建一个多线程服务器.问题是我收到以下错误:
play.exceptions.JPAException:JPA上下文未初始化.当在应用程序中找到使用@ javax.persistence.Entity注释注释的一个或多个类时,JPA实体管理器将自动启动.
play.exceptions.JPAException:JPA上下文未初始化.当在应用程序中找到使用@ javax.persistence.Entity注释注释的一个或多个类时,JPA实体管理器将自动启动.
我想要做的是从新线程访问db,这里是代码
- 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,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();
- }
- }
- }
- }
有任何想法吗?
解决方法
不要使用普通线程,而是使用作业:
- @OnApplicationStart
- public class MainLoop extends Job {
- public void doJob() {
- new BallJob().now();
- }
- }
和球手:
- public class BallJob extends Job {
- public void doJob() {
- List<Ball> balls;
- new Ball(5,15);
- while (true){
- balls = Ball.all().fetch();
- for (Iterator iterator = balls.iterator(); iterator.hasNext();) {
- Ball ball = (Ball) iterator.next();
- ball.applyForces();
- }
- }
- }