我正在将Google App Engine(Java)与Objectify 4.0b3配合使用,并希望拥有带有子类SportFacility和UserDefinedFacility的超类设施。我希望能够通过id查询设施,从而从所有子类中获取设施,并且我也希望能够对每个子类都做同样的事情。

@Entity
public class Facility {

    @Id
    protected Long id;
    @Index
    protected String name;
    @Index
    protected double x_coordinate;
    @Index
    protected double y_coordinate;
    @Index
    protected String address;

    protected Facility(){}

    public Facility(String name, double x_coordinate, double y_coordinate, String address) {
        this.name = name;
        this.x_coordinate = x_coordinate;
        this.y_coordinate = y_coordinate;
        this.address = address;
}

@EntitySubclass(index=true)
public class SportFacility extends Facility{

    @Index
    private String url;

    private void SportFacility(){}

    public SportFacility(String name, double x_coordinate, double y_coordinate, String address, String url) {
        super(name, x_coordinate, y_coordinate, address);
        this.url = url;
    }
}


@EntitySubclass(index=true)
public class UserDefinedFacility extends Facility{

    @Index
    private String url;

    private void UserDefinedFacility(){}

    public UserDefinedFacility(String name, double x_coordinate, double y_coordinate, String address) {
        super(name, x_coordinate, y_coordinate, address);

    }
}


基本上我的问题与Entity hierarchies in Objectify 4.0中描述的相同,但在我的情况下,查询

Facility facility = ofy().load().type(Facility.class).id(id);


无法工作,因为AndroidStudio抱怨该类型应为

LoadResult<Facility>


而不是设施。

由于继承概念的语法似乎在Objectify版本之间经常变化,因此我找不到有效的解决方案,因此,我非常感谢您的帮助!

提前致谢

塞缪尔

最佳答案

Android Studio是正确的;要获取实体本身,您需要:

Facility facility = ofy().load().type(Facility.class).id(id).now();

要么

Facility facility = ofy().load().type(Facility.class).id(id).safe();

如果该实体不存在,则后者将抛出一个NotFoundException(我记得现在将返回null)。

关于java - EntitySubclass对象化查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26899472/

10-10 04:26