Ebean OrderBy CASE WHEN

时间:2014-10-08 15:41:20

标签: playframework-2.0 ebean

使用Ebean finder时,是否可以按以下方式提供order by语句:

ORDER BY 
   CASE
      WHEN a = 'FOO' THEN 1
      WHEN a = 'BAR' THEN 2
      ELSE 99
   END

1 个答案:

答案 0 :(得分:3)

可以进行这样的排序。我们所要做的就是添加瞬态字段并使用带有适当参数的@Formula进行注释。

因此模型类应该如下所示:

@Entity
public class A extends Model {

    public A(Long aId, String aA) {
        id = aId;
        a = aA;
    }

    @Id
    public Long id;

    @Required
    public String a;

    @Transient
    @Formula(select = "(case when ${ta}.a = 'FOO' then 1 when a = 'BAR' THEN 2 else 99 end)")
    Integer index;

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

这样我们就创建了虚拟列'index',我们可以按它排序。

以下是示例性测试方法:

@Test
public void aTest() {
    FakeApplication app = Helpers.fakeApplication(Helpers.inMemoryDatabase());
    Helpers.start(app);

    A a1 = new A(1L, "BAR");
    A a2 = new A(2L, "XYZ");
    A a3 = new A(3L, "FOO");
    A a4 = new A(4L, "AAA");
    A a5 = new A(5L, "FOO");
    A a6 = new A(6L, "BAR");

    a1.save();
    a2.save();
    a3.save();
    a4.save();
    a5.save();
    a6.save();

    List<A> list = Ebean.find(A.class).orderBy("index").findList(); 
    for(A fa: list) {
        System.out.println("fa.id:"+fa.id+" fa.a:"+fa.a);
    }

    System.out.println("-------------------------");

    List<A> list1 = A.find.orderBy("index").findList();     
    for(A fa: list1) {
        System.out.println("fa.id:"+fa.id+" fa.a:"+fa.a);
    }
}