我有以下情况:
“帐户”类,它应该包含“货币”对象的集合。
@PersistenceCapable
public class Account extends Entity {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
private String id;
@Expose
@Persistent
private String name;
/**
* The initial balance should be a portfolio, e.g. 300 BGN, 230 EUR etc.
*/
@Expose
@Persistent
private List<Money> initialBalancePortfolio;
“金钱”类看起来是这样的:
public class Money {
@Persistent
@Extension(vendorName = "datanucleus", key = "gae.unindexed", value = "true")
private BigDecimal ammount;
@Persistent
private String currency;
问题来了:
这个测试用例显示了这个问题:
@Test
public void initialBalancePortfolioShouldBePersisted() throws Exception {
//create
Account account = createAccount();
AccountDao accountDao = new AccountDao();
accountDao.create(account);
//get it with new dao
AccountDao newAccountDao = new AccountDao();
Account newAccount = newAccountDao.readAll().get(0);
assertEquals(account.getInitialBalancePortfolio(), newAccount.getInitialBalancePortfolio());
}
private Account createAccount() {
//create list with money
List<Money> money = new ArrayList<Money>();
Money m1 = new Money(23, "BGN");
Money m2 = new Money(21, "EUR");
money.add(m1);
money.add(m2);
//create account
Account account = new Account(accEntity, money, "xxx");
return account;
}
和JUnit例外:
java.lang.AssertionError: expected:<[Money [ammount=23, currency=BGN], Money [ammount=21, currency=EUR]]> but was:<[Money [ammount=null, currency=null], Money [ammount=null, currency=null]]>
编辑:
用于创建对象的持久性代码:
/**
* Create entity. entityDao.create(entity);
*
* @param t
* Entity
* @return operations success
*/
public boolean create(T t) {
if (t.getId() == null) {
PersistenceManager pm = PMF.getInstance().getPersistenceManager();
try {
pm.makePersistent(t);
LOGGER.info(getEntityClass() + " created!");
return true;
} finally {
pm.close();
}
} else {
LOGGER.info(getEntityClass() + " already exist! Update only!");
update(t);
return false;
}
}
对于对象检索:
/**
* Get all existing objects.
*
* @return
*/
public List<T> readAll() {
PersistenceManager pm = PMF.getInstance().getPersistenceManager();
try {
pm.getFetchPlan().setGroup(FetchGroup.ALL);
Query q = pm.newQuery(getEntityClass());
@SuppressWarnings("unchecked")
List<T> allEntities = (List<T>) q.execute();
return allEntities;
} finally {
pm.close();
}
}
发布于 2014-01-05 22:52:20
我已经找到了解决这个问题的办法。
关于JDO如何管理对象生命周期的一些背景信息:transition.html
解决方案本身:
PersistenceManager pm = PMF.getInstance().getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
pm.makePersistent(t);
tx.commit();
} catch (Exception e) {
LOGGER.severe("Exception by creating a new entity "
+ e.getMessage());
tx.rollback();
} finally {
pm.close();
}
如您所见,我使用一个事务来确保对象处于有效状态。
https://stackoverflow.com/questions/20937219
复制相似问题