Default routing. EDIT template with composite key in crud Play 1.2.4

I have a composite key of user id and user role in my database.

To compare the database with the model below is the code:

@Id @Column(name="ID") public int userId; @Id @Column(name="USER_ROLE") public String userRole; ...... ...... @Override public String toString() { return userId; } 

Currently, I can display a list of users, as well as add a new user to my application. But when I try to switch to the default "Edit" template by clicking on the user ID, I get the error message "No route."

In addition, I see that when the user clicks the composite identifier does not receive send as the URL, in fact, some object is added at the end of the URL (which may be the reason for this).

Please let me know how to display the default editing screen when we have a composite key in the database. I have been struggling with this problem for a very long time, but have not received any reference materials in the documentation :(

+7
source share
1 answer

The Play CRUD controller does not work well with composite keys. Here you can get around this.

First, define the string format for your composite keys - in the example below, I just took two keys (ssn, accountId) and merged them into a "-" section.

In your model, override the _key and findById from GenericModel and JPABase as follows:

 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; } } 

Next, override the show method in your controller:

  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); } } 

What is it.

+2
source

All Articles