Play Framework: Inheritance sort by type

ぐ巨炮叔叔 提交于 2019-12-01 14:29:39

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.

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