java - Play framework 2.2.0 不会自动生成 getter/setter

标签 java scala playframework-2.2

在处理 Play 框架时,我发现了非常烦人的情况,我不得不花很多时间来指出罪恶的根源在哪里!

为了简化情况,让我们考虑下面的代码:

controllers.Application.java 中:

return ok(views.html.method1.render(Person.find.all());

method1.scala.html 中:

@(people : List[Person])
...
@for(person <- people) {
     @person.name
     @person.pet.getName()
     @person.pet.name
}

Person.java 中:

@Id
public Long id;
@ManyToOne
public Pet name;
...

问题是当我在 Pet 类中手动设置 getName() 方法时。该值被返回。 但是当我让 Play 框架自动生成时,它没有返回任何值!

当然,Play 框架已经为 person 生成了 getter,我可以通过 person.name 访问它。

它不是应该自动生成的吗?

最佳答案

http://www.playframework.com/documentation/2.2.x/JavaEbean指出 getter 和 setter 是在运行时生成的(对于需要它们的普通旧 Java 库)并且在编译时不可见:

Play has been designed to generate getter/setter automatically, to ensure compatibility with libraries that expect them to be available at runtime (ORM, Databinder, JSON Binder, etc). If Play detects any user-written getter/setter in the Model, it will not generate getter/setter in order to avoid any conflict.

Caveats:

(1) Because Ebean class enhancement occurs after compilation, do not expect Ebean-generated getter/setters to be available at compilation time. If you’d prefer to code with them directly, either add the getter/setters explicitly yourself, or ensure that your model classes are compiled before the remainder of your project, eg. by putting them in a separate subproject.

(2) Enhancement of direct Ebean field access (enabling lazy loading) is only applied to Java classes, not to Scala. Thus, direct field access from Scala source files (including standard Play templates) does not invoke lazy loading, often resulting in empty (unpopulated) entity fields. To ensure the fields get populated, either (a) manually create getter/setters and call them instead, or (b) ensure the entity is fully populated before accessing the fields.

因此 setter/getter 在您的模板中不可见。 如果您需要延迟加载(请参阅2)),我建议您让您的 getter 和 setter 由您的 IDE 生成。 如果您不需要延迟加载,只需访问这些字段,无论如何它们都是public

顺便说一句:在类 Person 中对名为 name 的类 Pet 的引用听起来像是一个尴尬的数据模型,没有冒犯。

关于java - Play framework 2.2.0 不会自动生成 getter/setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19567693/

相关文章:

java - 为什么变量在没有同步的情况下对其他线程可见?

scala - 如何在scala程序中的vs代码中设置断点

json - Play 框架 scala json 验证异常

scala - 播放2配置文件: Reading a list of string variable

scala - 在 Play Framework 中使用可选的 GET 参数反向路由

java - 需要帮助了解 Java 中比较器接口(interface)的内部工作原理

java - 使用 JUnit 测试数据库中的 CRUD 操作

java - 当两个泛型参数具有相同的上限时,未经检查的强制转换警告

java - 使用 PlayWS 通过 Java 创建 WSClient - Materializer null

scala - asInstanceOf[T] 和 (o : T) in Scala?