我是Play的新手,我正在努力实现Canteen和OpeningTimes之间的OneToOne关系,我想1:1就是我想要的。但是我得到一个NullPointerException ...
@Entity
public class OpeningTimes extends Model {
@Id
public Long id;
@Required
public String mondayHours;
@Required
public String tuesdayHours;
...
@OneToOne
public Canteen canteen;
}
@Entity
public class Canteen extends Model {
@Id
public Long id;
...
@OneToOne
public OpeningTimes openingTimes;
}
这里我填充了数据库
public class Global extends GlobalSettings {
@Override
public void onStart(Application arg0) {
if(Canteen.finder.findRowCount() == 0) {
Canteen canteen = new Canteen();
...
canteen.save();
Canteen canteen1 = new Canteen();
...
canteen1.save();
OpeningTimes times = new OpeningTimes();
times.mondayHours = "7:00 - 15:00";
times.tuesdayHours = "7:00 - 15:00";
...
times.canteen = canteen;
times.save();
OpeningTimes times1 = new OpeningTimes();
times1.mondayHours = "7:00 - 15:00";
times1.tuesdayHours = "7:00 - 15:00";
...
times1.canteen = canteen1;
times1.save();
}
show.scala.html
@(canteen: Canteen)
@main("MamHlad | " + canteen.nameShort) {
<h1>@canteen.nameFull</h1>
<h2>Opening times</h2>
** <p>@canteen.openingTimes.mondayHours</p> **
<p>@canteen.openingTimes.tuesdayHours</p>
}
Asterixes标记它抛出NullPointerException的行,这里是堆栈跟踪
! @6c6cgmg4b - Internal server error, for request [GET /canteens/2] ->
play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[NullPointerException: null]]
at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:134) [play_2.9.1.jar:2.0.4]
at play.core.ActionInvoker$$anonfun$receive$1.apply(Invoker.scala:115) [play_2.9.1.jar:2.0.4]
at akka.actor.Actor$class.apply(Actor.scala:318) [akka-actor.jar:2.0.2]
at play.core.ActionInvoker.apply(Invoker.scala:113) [play_2.9.1.jar:2.0.4]
at akka.actor.ActorCell.invoke(ActorCell.scala:626) [akka-actor.jar:2.0.2]
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:197) [akka-actor.jar:2.0.2]
Caused by: java.lang.NullPointerException: null
at views.html.show$.apply(show.template.scala:37) ~[classes/:na]
at views.html.show$.render(show.template.scala:105) ~[classes/:na]
at views.html.show.render(show.template.scala) ~[classes/:na]
at controllers.Application.show(Application.java:23) ~[classes/:na]
at Routes$$anonfun$routes$1$$anonfun$apply$5$$anonfun$apply$6.apply(routes_routing.scala:76) ~[classes/:na]
at Routes$$anonfun$routes$1$$anonfun$apply$5$$anonfun$apply$6.apply(routes_routing.scala:76) ~[classes/:na]
提前感谢您的帮助!
答案 0 :(得分:2)
我发现你没有指定OneToOne关系的拥有方,这是强制性的。
@Entity
public class OpeningTimes extends Model {
@Id
public Long id;
...
@OneToOne(mappedBy="openingTimes", cascade=CascadeType.ALL)
public Canteen canteen;
}
另外我认为你需要使用setOpeningTimes方法,而不是直接访问属性。像这样,
canteen.setOpeningTimes(openingTime1);
canteen.save();