2

我的项目中有一个模型类“Journey”,它有几种删除、创建和列出所有旅程的方法。我正在使用 heroku 和一个 postgresql 数据库。我需要编写一种方法,将所有与指定地址具有相似地址的旅程返回。我知道查询结构通常是这样的,SELECT address FROM Journey WHERE address ~~ arguement但我不知道在播放框架中存在哪些函数来执行此操作。

*public static void search(String address){
//query
//return matching journey results
}*
4

1 回答 1

5

您需要以模型Finder为例:

package models;

import play.db.ebean.Model;

import javax.persistence.*;

@Entity
public class Journey extends Model {

    @Id
    public Integer id;

    public static Finder<Integer, Journey> find
            = new Model.Finder<>(Integer.class, Journey.class);

    // other fields
    public String address;
    public String country;

}

因此您可以通过以下方式轻松选择记录:

List<Journey> allJourneys = Journey.find.all();
List<Journey> searchedJourneys = Journey.find.where().like("address", "%foo%").findList();
Journey firstJourney = Journey.find.byId(123);

在您的基本情况下,您可以将其添加到您的模型中:

public static List<Journey> searchByAddress(String address){
    return find.where().like("address", "%"+address+"%").findList();
}

等等。它返回带有关系的整个对象,因此在大数据集中它可能太重了,您可以甚至应该使用 Finder 的链式方法(例如 等)使用更优化的查询select()fetch()指出您目前需要的数据。

Ebean 的 API中还有其他可能性,无论如何您需要声明哪种方法最适合您。

顺便说一句,值得研究一下现有的示例应用程序,作为computer's database熟悉此 ORM 的示例。

编辑

对于不区分大小写的搜索,还有其他表达式,即(ilike而不是likeistartsWith、、、、和。他们在开始时没有相同的版本。iendsWithieqicontainsiexampleLikei

您也可以在 API中预览它们。

于 2013-02-19T18:57:01.200 回答