我在 Play 1.2.x 应用程序中发现了奇怪的行为
例如我们有以下代码:
app/models/Account.java:
package models;
import javax.persistence.Entity;
import play.db.jpa.Model;
@Entity
public class Account extends Model {
public String username;
}
app/coutrollers/Application.java:
package controllers;
import play.mvc.Controller;
import java.util.List;
import models.Account;
public class Application extends Controller {
public static void index() {
Account account = Account.find("username LIKE ?", "username1").first();
account.username = "username3";
List<Account> accounts = Account.all().fetch();
render(account, accounts);
}
}
app/views/Application/index.html:
#{extends 'main.html' /}
#{set title:'Home' /}
<h2>Working!</h2>
${account.username}
<ul>
#{list items:accounts, as:'acc'}
<li>${acc.username}</li>
#{/list}
</ul>
数据库中有以下帐户:
- 用户名1
- 用户名2
输出如下:
工作!
用户名3
- 用户名3
- 用户名2
但必须是:
工作!
用户名3
- 用户名1
- 用户名2
这是什么???
- Play 错误?
- Java 静态上下文功能?
- JPA 功能?
- ...?
已解决
感谢@millimoose。所需要的只是一个detach()
:
package controllers;
import play.mvc.Controller;
import java.util.List;
import models.Account;
import play.db.jpa.JPA;
public class Application extends Controller {
public static void index() {
Account account = Account.find("username LIKE ?", "username1").first();
account.username = "username3";
JPA.em().detach(account);
List<Account> accounts = Account.all().fetch();
render(account, accounts);
}
}
最佳答案
JPA 的工作方式与地球上所有其他 ORM 一样,当您两次查找相同的数据库记录时,您将获得相同的对象。 .first()
查询在内部缓存 Account
(以跟踪工作单元内对其所做的更改),以及 .all().fetch ()
调用只是再次为您提供该缓存的对象。
我对Play不熟悉! ORM 的东西,但“原始”JPA 有 EntityManager.detach()
使其停止跟踪给定的实体实例。 (因此,每当再次检索相应的数据库记录时,都会为您提供一个新副本。)
关于java - Play 1.2.x 使用数据库时出现奇怪的事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15498612/