OrderBy
クエリビーンのプロパティは、orderBy句に追加されるように asc() と desc() メソッドを持っています。
List<Customer> customers =
new QCustomer()
.status.in(Status.NEW, Status.ACTIVE)
.orderBy()
.name.desc() // order by t0.name desc
.findList();
以下のSQLが生成されます
select ...
from customer t0
where t0.status in (?, ?)
order by t0.name desc
複数のプロパティをorderBy句に追加できます。
List<Customer> customers =
new QCustomer()
.status.in(Status.NEW, Status.ACTIVE)
.orderBy()
.name.desc()
.id.asc()
.findList();
標準のorderBy
標準のクエリでは、orderBy().desc() または orderBy().asc() を使用します。これらは連鎖させることもできます。前のクエリと同じものがクエリビーンなしで書かれたものが次のとおりです
List<Customer> customers = database.find(Customer.class)
.where().in("status"), Status.NEW, Status.ACTIVE)
.orderBy()
.desc("name")
.asc("id")
.findList();
OrderBy式
SQLの式を含む順序指定式は、orderBy(文字列) を介して指定できます。
例: 単純な式
new QCustomer()
.orderBy("name asc,status desc")
.findList()
例: DB関数を用いた式
List<Customer> customers =
new QCustomer()
.status.in(Status.NEW, Status.ACTIVE)
.orderBy("coalesce(activeDate, now()) desc, name, id")
.findList();
Nulls high、Nulls low
orderBy式には、nulls high または nulls low を含めることができます。
List<Customer> customers =
new QCustomer()
.orderBy("name nulls high, id desc")
.findList();
照合
asc() と desc() を介して使用する照合を指定できます。
List<Customer> customers =
new QCustomer()
.orderBy()
.asc("name", "latin_2");
.desc("id", "latin_1");
.findList();
toManyの順序指定
maxRows または fetchQuery の使用によりORMクエリが複数のSQLクエリとして実行された場合(フェッチルールを参照)、toManyリレーションシップに対応するorderBy式は適切なSQLクエリに自動的に移動されます。
例
QContact contact = QContact.alias();
List<Customer> customer =
new QCustomer()
.contacts.fetch(contact.firstName, contact.lastName, contact.email)
.orderBy()
.name.asc()
.contacts.email.asc() // (1) automatically moved to secondary sql query
.setMaxRows(10) // (2) maxRows
.findList();
maxRowsにより、上記のORMクエリは2つのSQLクエリとして実行されます。詳しくは、フェッチルールを参照してください。
-- Primary query
select t0.id, t0.status, t0.name, ...
from customer t0
order by t0.name
limit 10 -- (2)
-- Secondary query
select t0.customer_id, t0.id, t0.first_name, t0.last_name, t0.email
from contact t0
where (t0.customer_id) in (? )
order by t0.email -- (1)