4
當使用取景器Ebean,是有可能通過聲明類似下面提供了一個命令:Ebean排序依據CASE WHEN
ORDER BY
CASE
WHEN a = 'FOO' THEN 1
WHEN a = 'BAR' THEN 2
ELSE 99
END
當使用取景器Ebean,是有可能通過聲明類似下面提供了一個命令:Ebean排序依據CASE WHEN
ORDER BY
CASE
WHEN a = 'FOO' THEN 1
WHEN a = 'BAR' THEN 2
ELSE 99
END
這是可以做到這樣的排序。我們所要做的就是添加瞬態場,並用@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);
}
這種方式,我們創建的虛擬列「指數」,我們可以通過它進行排序。
下面是示例性的測試方法:
@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);
}
}