Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The Play CRUD controller doesn't work well with composite keys. Here's how you can work around it.</p> <p>First, decide on a stringified format for your composite keys - in the example below I've just taken the two keys (ssn, accountId) and concatenated them separated with a "-".</p> <p>In your model override the <code>_key</code> and <code>findById</code> methods from GenericModel and JPABase as follows:</p> <pre><code>package models; import play.db.jpa.GenericModel; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Part extends GenericModel { @Id public int ssn; @Id public int accountId; public String name; /** * Find a part by its composite id ("ssn-accountId") */ public static Part findById(String id) { // Split the composite id to extract ssn and accountId String[] elements = id.split("-"); int ssn = Integer.valueOf(elements[0]); int accountId = Integer.valueOf(elements[1]); return Part.find("ssn=? AND accountId=?", ssn, accountId).first(); } /** * Return a composite id ("ssn-accountId") */ public String _key() { return ssn + "-" + accountId; } } </code></pre> <p>Next override the <code>show</code> method in your controller:</p> <pre><code> package controllers; import models.Part; public class Parts extends CRUD { /** * CRUD show method doesn't know how to handle composite ids. * * @param id composite of ssn + "-" + accountId * @throws Exception */ public static void show(String id) throws Exception { // Do not rename 'type' or 'object' ObjectType type = ObjectType.get(getControllerClass()); notFoundIfNull(type); Part object = Part.findById(id); notFoundIfNull(object); render("CRUD/show.html", type, object); } } </code></pre> <p>That's it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload