【问题标题】:Play Framework: Inheritance sort by typePlay Framework:按类型排序的继承
【发布时间】:2014-10-21 21:08:24
【问题描述】:

在我的应用程序中,我有 2 个类:

- Group
- Model

还有一个基类Element

我使用单表策略来持久化这些模型。 (strategy = InheritanceType.SINGLE_TABLE)。因此在我的表中创建了一个列dtype

我现在正在尝试根据这种类型对我的页面进行排序:

find.where().disjunction()
                .add(Expr.ilike("name", "%" + filter + "%"))
                .orderBy("dtype asc, name asc," + sortBy + " " + order).findList()

但这会引发异常,无法找到该 dtype。

如何根据类型进行排序?

谢谢!

【问题讨论】:

  • 嗯,但是如果您在 Element 中声明了 find 方法,它总是只选择带有 dtype = 'Element' 的行,不是吗?在这种情况下,没有必要按它进行排序。
  • 好吧,我希望 GroupModel 两个类都出现在搜索中。所以我在基类(Element)上使用 find 。但我希望 Group 中的 Objects 出现在 Model 之前。
  • 刚刚创建了一个带有继承表的示例应用程序,可以在查找器中使用鉴别器字段...不过还有一些工作要做:)
  • 谢谢。您的解决方案效果很好。如果您发布答案,我非常乐意接受。

标签: jpa playframework-2.0 ebean


【解决方案1】:

示例基本模型如下所示:

package models.db;

import play.db.ebean.Model;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "content")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("content")
public abstract class Content extends Model {

    @Id
    public Long id;

    @Column(name = "dtype", insertable = false, updatable = false)
    public String dtype;

    public static Finder<Long, Content> find = new Finder<>(Long.class, Content.class);

    public String title;
    public Date created = new Date();
    public Date modified = new Date();


}

然后你可以像这样扩展它:

package models.db;

import javax.persistence.*;

@Entity
@DiscriminatorValue("news")
public class News extends Content {

    @Id
    public Long id;
    public static Finder<Long, News> find = new Finder<>(Long.class, News.class);

    public String newsSource;

}

package models.db;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;

@Entity
@DiscriminatorValue("post")
public class Post extends Content {

    @Id
    public Long id;
    public static Finder<Long, Post> find = new Finder<>(Long.class, Post.class);

    public Date publishDate;

}

因此您可以通过以下方式选择所有内容:

List<Content> contents = Content.find.where().orderBy("dtype ASC").findList();

当然,这些对象将只有共享字段:iddtypetitlecreatedmodified,用于获取即(新闻)newsSource 或(发布)publishDate 你需要使用自己的查找器获取这些对象,即使用 general 内容查询中的 id 值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-19
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多