gpt4 book ai didi

java - OneToOne 对象为空

转载 作者:太空宇宙 更新时间:2023-11-04 14:23:11 28 4
gpt4 key购买 nike

我正在使用 play 框架 (v2.3.1),并且我有 2 个模型对象;用户和位置。他们彼此之间存在一对一的关系。保存按预期进行,但是当我想从数据库中检索用户时,该位置为空。

我的类(class):

@Entity
public class Location extends Model
{
public static Finder<Long, Location> find = new Finder<Long, Location>(Long.class, Location.class);

@OneToOne
@Id
public Long id;

@Constraints.Required
@Formats.NonEmpty
public String name;

public Location(String name)
{
this.name = name;
}

@Override
public String toString()
{
return id+":"+name;
}
}

@Entity
public class User extends Model
{
public static Finder<Long, User> find = new Finder<Long, User>(Long.class, User.class);

@Id
public Long id;

@Constraints.Required
@Formats.NonEmpty
@Column(unique = true)
public String email;

public String name;

@OneToOne
@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "location_id")
public Location location;

public User(String email, String name, Location location)
{
this.email = email;
this.name = name;
this.location = location;
}

public static User getByEmail(String email)
{
return find.where().eq("email", email).findUnique();
}
}


public class Application extends Controller {

public static Result index()
{
User user = User.getByEmail("random@mail.com");
return ok( user.name + "\t" + user.location );
}
}

示例输出为:Some Person 2:null

已收到位置 ID,但名称变量具有空值。获取用户后如何获取要填充的位置对象?

最佳答案

默认情况下,所有关系都会被延迟加载。这意味着,所有实体引用(来自另一个表的实体引用默认情况下不会加载( FetchType.LAZY ))。所以你应该指定你想要急切地加载它。像这样

@OneToOne(fetch=FetchType.EAGER)

关于java - OneToOne 对象为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26963576/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com