[英]Strange thing in Play 1.2.x when working with database
我在Play 1.2.x應用程序中發現了奇怪的行為
例如,我們有以下代碼:
應用程序/模型/ Account.java:
package models;
import javax.persistence.Entity;
import play.db.jpa.Model;
@Entity
public class Account extends Model {
public String username;
}
應用程序/ 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);
}
}
應用程序/視圖/應用/ 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>
在數據庫中具有以下帳戶:
輸出如下:
USERNAME3
但必須為:
USERNAME3
這是什么???
感謝@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()
使其停止跟蹤給定的實體實例。 (因此,每當再次檢索到相應的數據庫記錄時,就給您一個新副本。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.