OneToOne对象为空

时间:2014-11-17 00:03:42

标签: java playframework ebean

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

我的课程:

@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,但name变量的值为空。如何在获取用户后获取Location-object?

2 个答案:

答案 0 :(得分:0)

从您的帖子我假设Location是父实体,User是子实体。

@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实体时,上述location会很有用,同时您可以获取关联的user实体。

@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

检索位置名称

答案 1 :(得分:0)

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

@OneToOne(fetch=FetchType.EAGER)