playframework-1.x - 为什么我的嵌套 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();
}
解决方案
尝试更改以下行
<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 加载相关实体。
推荐阅读
- python - 操作系统错误,没有这样的文件或目录:我无法安装某些软件包
- gcc - ARM GCC Cortex-M7 裸机编译器标志,用于正确的浮点堆栈对齐?
- bash - 如果 VPS1 失败或向 VPS2 发送一些任务,我如何让 VPS2 自动工作?
- python - Python、Windows:术语“conda”未被识别为 cmdlet 的名称
- python - 如何循环 BeautifulSoup 的 URL 输出?
- common-lisp - set-dispatch-macro-character 的完整文档在哪里?
- swift - Swift 使用 Delegate 刷新 Tableview
- reactjs - 如何使用不同的 React.render() 函数在组件之间共享数据
- scrapy - Scrapy KeyError(f"{self.__class__.__name__} 不支持字段:{key}"
- html - 在单独的行中显示两个 td