Play Framework: Inheritance sort by type

試著忘記壹切 提交于 2019-12-04 02:24:11

问题


In my Application, I have 2 Classes:

- Group
- Model

and one base class Element.

I use the single table strategy to persist these models. (strategy = InheritanceType.SINGLE_TABLE). Thus a column dtypeis created in my table.

I'm now trying to sort my pages based on this type:

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

But this throws an Exception, that dtype cannot be found.

How can I sort based on the type?

Thanks!


回答1:


Sample base model can look like:

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();


}

Then you can extend it like:

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;

}

or

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;

}

So you can choose all contents via:

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

Of course these objects will have only shared fields: id, dtype, title, created and modified, for getting i.e. (News) newsSource or (Post) publishDate you need to get these objects with their own finders i.e. using id value from general Content query.



来源:https://stackoverflow.com/questions/26496358/play-framework-inheritance-sort-by-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!