(Reference) Books you are studying https://www.amazon.co.jp/Play-Framework-2%E5%BE%B9%E5%BA%95%E5%85%A5%E9%96%80-Java%E3%81%A7%E3%81%AF%E3%81%98%E3%82%81%E3%82%8B%E3%82%A2%E3%82%B8%E3%83%A3%E3%82%A4%E3%83%ABWeb%E9%96%8B%E7%99%BA-%E6%B4%A5%E8%80%B6%E4%B9%83/dp/4798133922/ref=cm_cr_srp_d_product_top?ie=UTF8
In the play framework, the search function is grouped in a class called Model.Finder. The basic usage is to create an instance in Model and retrieve it as needed.
new Finder<Primary key,entity>(Primary key.class,entity.class);
Save the created instance in the static field, and retrieve the entity with that method if necessary.
public String toString() {
return ("[id:"+id+",name:"+name+",mail:"+mail+",message:"+message+",date:"+postdate+"]");
}
Override the toString method of the object class for clarity (Reference about object class) https://docs.oracle.com/javase/jp/7/api/java/lang/Object.html
package models;
import java.util.Date;
import javax.persistence.*;
import javax.validation.*;
import play.data.validation.*;
import play.db.ebean.*;
@Entity
public class Message extends Model {
@Id
public Long id;
public String name;
public String mail;
public String message;
public Date postdate;
public static Finder<Long,Message>find = new Finder<Long,Message>(Long.class,Massage.class);
@Override
public String toString() {
return ("[id:"+id+",name:"+name+",mail:"+mail+",message:"+message+",date:"+postdate+"]");
}
}
Describe the settings so that the entity can be retrieved from the controller class.
List<entity>Variable = Finder instance.all();
A Java List is an ordered collection that can contain duplicate elements. (What is Reference List) https://eng-entrance.com/java-array-list#List
List<Message>datas=Message.find.all();
You are calling the all method of the find instance. The all method returns all the stored methods in a List.
package controllers;
import play.*;
import play.mvc.*;
import views.html.*;
public class Application extends Controller {
//Action when accessing the route
public static Result index(){
List<Message>datas=Message.find.all();
return ok(index.render("Database sample"));
}
}
Change the received list so that it can be output as it is.
@(msg:String,datas:List[Message])
@main("Sample page") {
<h1>Hello!</h1>
<p>@msg</p>
<pre>@datas</pre>
}
Recommended Posts