首页 > 解决方案 > 为什么我的嵌套 POJO 从 Play 中的表单返回 null!1.x

问题描述

在玩!框架 1.5.1,为什么我会为 thingy.Owner 获得空值?自动绑定不应该解决这个问题吗?

用户类

    package models;

@Entity
@Table(name="objtest_user")
public class User extends Model
{
    @Required
    public String username;

    @Password
    @Required
    public String password;

    public String fullname;

    public User(String username, String password, String fullname)
    {
        this.username = username;
        this.password = password;
        this.fullname = fullname;
    }

    @Override
    public String toString()
    {
        return this.fullname;
    }
}

以及引用 User 类的 Thingy 类

    package models;

import java.util.*;
import javax.persistence.*;

import play.db.jpa.*;
import play.data.validation.*;

@Entity
public class Thingy extends Model
{
    @Required
    public String Name;

    @ManyToOne
    public User Owner;

    public Thingy(String name, User owner)
    {
        this.Name = name;
        this.Owner = owner;
    }

    @Override
    public String toString()
    {
        return Name;
    }
}

和这个模板表格

#{extends 'main.html' /}
#{set title:'Home' /}

<p>Current user = ${currentUser}</p>


#{form @saveThingy(), id:'saveThingy'}
    <input type="text" id="thingy.Name" name="thingy.Name"/>
    <input type="hidden" id="thingy.Owner" name="thingy.Owner" value="${currentUser}"/>
    <input type="submit" id="Save" value="Save"/>
#{/form}

控制器方法

public static void saveThingy(Thingy thingy)
{
    System.out.println("Name = " + thingy.Name);
    System.out.println("Owner = " + thingy.Owner);

    thingy.save();
}

标签: playframework-1.x

解决方案


尝试更改以下行

<input type="hidden" id="thingy.Owner" name="thingy.Owner" value="${currentUser}"/>

<input type="hidden" id="thingy.Owner" name="thingy.Owner.id" value="${currentUser.id}"/>

如果您查看文档 ( https://www.playframework.com/documentation/1.2.x/controllers#params ),并查找 JPA 对象绑定部分,它会谈到要求子对象具有 id。当它找到一个对象的 ID 时播放,它将通过 JPA/Hibernate 加载相关实体。


推荐阅读