Java 一个对象是空的
我正在使用play框架(v2.3.1),我有两个模型对象;用户和位置。他们之间有着一对一的关系,彼此之间相互依赖。保存按预期进行,但当我想从数据库检索用户时,该位置为空 我的班级:Java 一个对象是空的,java,playframework,ebean,Java,Playframework,Ebean,我正在使用play框架(v2.3.1),我有两个模型对象;用户和位置。他们之间有着一对一的关系,彼此之间相互依赖。保存按预期进行,但当我想从数据库检索用户时,该位置为空 我的班级: @Entity public class Location extends Model { public static Finder<Long, Location> find = new Finder<Long, Location>(Long.class, Location.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 );
}
}
@实体
公共类位置扩展模型
{
公共静态查找器find=新查找器(Long.class、Location.class);
@奥内托内
@身份证
公共长id;
@约束条件。必需
@格式。非空
公共字符串名称;
公共位置(字符串名称)
{
this.name=名称;
}
@凌驾
公共字符串toString()
{
返回id+“:”+名称;
}
}
@实体
公共类用户扩展模型
{
publicstaticfinder=newfinder(Long.class,User.class);
@身份证
公共长id;
@约束条件。必需
@格式。非空
@列(唯一=真)
公共字符串电子邮件;
公共字符串名称;
@奥内托内
@PrimaryKeyJoinColumn(name=“id”,referencedColumnName=“location\u id”)
公共场所;
公共用户(字符串电子邮件、字符串名称、位置)
{
this.email=电子邮件;
this.name=名称;
这个位置=位置;
}
公共静态用户getByEmail(字符串电子邮件)
{
返回find.where().eq(“email”,email).findUnique();
}
}
公共类应用程序扩展控制器{
公共静态结果索引()
{
User=User.getByEmail(“random@mail.com");
返回ok(user.name+“\t”+user.location);
}
}
示例输出为:someperson2:null
接收到位置id,但名称变量的值为空。获取用户后如何获取要填充的位置对象?从您的帖子中,我假设
位置
是父实体,用户
是子实体
@Entity
public class Location extends Model
{
@Id
public Long id;
// Following field won't persist in database, it will fetch the matching user object based on location_id in the user table.
@OneToOne(mappedBy = "location")
public User user;
// .............
}
当您获取位置
实体时,上面的mappedBy将非常有用,同时您可以获取关联的用户
实体
@Entity
public class User extends Model
{
@OneToOne
@JoinColumn(name = "location_id")
// Above annotation will create a new column in the name of location_id in user table, will be the foreign key of id in the Location table.
public Location location;
// .............
}
您最终可以通过user.location.name
检索位置名称。默认情况下,所有关系都会被加载。这意味着,默认情况下不会加载所有实体引用(来自另一个表(FetchType.LAZY))。因此,您应该指定,您希望急切地加载它。像这样
@OneToOne(fetch=FetchType.EAGER)
这是如何解决的?同样的问题,id被填充,其余字段为空