我一直试图在 Twirl 模板中显示一对一关系的数据(使用 Play Framework Java - 2.5.10)。基本上我有一个用户模型:
package models;
import java.sql.Date;
import javax.persistence.*;
import com.avaje.ebean.Model;
@Entity
@Table(name = "users")
public class User extends Model {
@Id
@Column(name = "id")
public Long id;
@Column(name = "first_name")
public String firstName;
@Column(name = "middle_name")
public String middleName;
@Column(name = "last_name")
public String lastName;
@Column(name = "date_of_birth")
public Date dateOfBirth;
@Column(name = "sex")
public String sex;
@OneToOne
@JoinColumn(name = "time_zone_id")
public TimeZone timeZone;
public static Finder<Long, User> find = new Finder<>(User.class);
}
和农民模型:
package models;
import com.avaje.ebean.Model;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name="farmers")
public class Farmer extends Model {
public enum Status {INACTIVE, ACTIVE}
@Id
@Column(name="id")
public Long id;
@OneToOne(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="user_id")
public User user;
@Column(name="profile_pic_url")
public String profilePicUrl;
@Column(name="access_url")
public String accessUrl;
@Column(name="status")
public String status = Status.INACTIVE.name();
@OneToMany(mappedBy = "farmer", targetEntity = Farm.class, fetch = FetchType.LAZY)
public List<Farm> farms;
public static Finder<Long, Farmer> find = new Finder<>(Farmer.class);
public static List<Farmer> getAllActive() {
return Farmer.find.where().eq("status", Status.ACTIVE.name()).findList();
}
}
请注意,有一个与用户模型一对一的获取类型设置为渴望。现在,我想在我的模板中显示农民的数据,其中农民的名字实际上是关联用户模型中的名字。
所以我在我的控制器中做了这个:
public class FarmerController extends Controller {
public Result all() {
return ok(farmers.render(Farmer.getAllActive()));
}
public Result farmer(Long id, String url) {
return ok(farmer.render());
}
}
现在这为我提供了正确的农民数据,但是当我尝试通过 User 模型显示名称时,我得到了 null。更具体地说,写这会导致空值(nullnull
实际上,我得到了):
<div><h4>@(farmer.user.firstName + farmer.user.lastName)</h4></div>
我错过了什么?