问题
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 dtype
is 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