我有两个简单的 Pojos 用户和评级。用户有一个嵌入的评级列表。这些类用@PersistenceCapable 注释,属性用@Persistent 注释。我写了一个简单的测试来创建一个用户,设置评级并将其持久化
PersistenceManager pm = PMF.get().getPersistenceManager();
pm.makePersistent(user);
当我像这样获取对象时,评级为空(不像我预期的那样):
User user = (User) pm.getObjectById(User.class, key);
我尝试了一些方法来解决问题:
当我使用 @Persistent(defaultFetchGroup = "true") 在 User 中注释属性评级时,列表包含一个带有键、父键等的对象,但该值从未设置(导致 0.0 而不是实际值)。
我可以通过在持久化数据之前额外设置一个事务来解决这个问题:
pm.currentTransaction().begin();
pm.makePersistent(user);
pm.currentTransaction().commit();
所以最后它与注释和事务一起工作。但这是为什么呢?本地单元测试(使用测试助手)、开发模式和部署在应用引擎上的行为是相同的。
我正在使用 App Engine SDK 1.8.1。此处参考用户、评级和测试:
@PersistenceCapable
public class User {
@PrimaryKey
@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
private Key key;
// if added ratings is fetched
@Persistent(defaultFetchGroup = "true")
private List<Rating> ratings;
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public List<Rating> getRatings() {
return ratings;
}
public void setRatings(List<Rating> ratings) {
this.ratings = ratings;
}
}
@PersistenceCapable
public class Rating {
@PrimaryKey
@Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private double rating;
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
}
@Test
public void testFindByIdWithExistingKey() throws DaoException {
User user = new User();
List<Rating> ratings = new ArrayList<Rating>();
Rating rating = new Rating();
rating.setRating(1.2);
ratings.add(rating);
user.setRatings(ratings);
Key key = persist(user);
User user2 = dao.findById(key);
Assert.assertEquals(1.2, user2.getRatings().get(0).getRating(), 0.0001);
}
private Key persist(User user) {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
//pm.currentTransaction().begin();
pm.makePersistent(user);
//pm.currentTransaction().commit();
return user.getKey();
} finally {
pm.close();
}
}
@Override
public User findById(Key key) throws DaoException {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
User user = (User) pm.getObjectById(User.class, key);
return user;
} catch (RuntimeException e) {
throw new DaoException("could not find user", e);
} finally {
pm.close();
}
}