我有两个简单的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();
}
}