在crud Play 1.2.4中使用复合键路由到默认的EDIT模板

use*_*944 7 java web-applications crud playframework playframework-1.x

我的数据库中有用户ID和用户角色的复合键.

为了使用模型映射DB,下面是代码:

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

目前,我能够显示用户列表,还能够为我的应用程序添加新用户.但是当我尝试通过单击用户ID路由到默认的"编辑"模板时,我收到一个错误:"无路由".

此外,我可以看到,在点击用户时,复合ID不会作为URL发送,实际上一些对象被附加在URL的末尾(这可能是这个的原因).

如果我们在数据库中有复合键,请告诉我如何显示默认编辑屏幕.我一直在努力解决这个问题很长一段时间但没有在文档中有任何参考资料:(

ct_*_*ct_ 2

Play CRUD 控制器不能很好地与复合键配合使用。以下是解决该问题的方法。

首先,决定复合键的字符串化格式 - 在下面的示例中,我刚刚获取了两个键(ssn、accountId)并将它们连接起来,并用“-”分隔。

在您的模型中,重写GenericModel 和 JPABase 中的_keyfindById方法,如下所示:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来重写show控制器中的方法:

    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);
    }
}
Run Code Online (Sandbox Code Playgroud)

就是这样。