简体   繁体   中英

Play Framework Database Search

I have a model class "Journey" in my project which has several methods to delete, create and list all of the journeys. I am using heroku and a postgresql database. I need to write a method that will return all journeys that have a similar address to one specified. I know the query structure would typically be something like SELECT address FROM Journey WHERE address ~~ arguement but I don't know what functions exist to do this in the play framework.

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

You need to use Model's Finder for an example:

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;

}

so you can easily select records with:

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

In your base case you can add this to your model:

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

Etc. It returns whole objects with relations, so in big data sets it can be too heavy, you can or even should also use more optimized queries with Finder's chained methods like select() , fetch() etc to point which data you need at the moment.

There are also other possibilities in Ebean's API , anyway you need to declare which approach is most optimal for you.

BTW, it's worthy to examine existing sample applications, for an example computer's database to get familiar with this ORM.

Edit

For case insesitive searching there are additional Expressions ie ilike (instead of like ) , istartsWith , iendsWith , ieq , icontains and iexampleLike . They does the same what version without i at the beginning.

You can preview them in the API as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM