JPA EntityManager在事务完成之前更新对象?

时间:2017-03-05 19:27:35

标签: java hibernate jpa

我有一种奇怪的行为。我有一个更新方法,它加载一个对象并更新那里的一些属性。在这个方法中,我还要查询对于更新很重要的其他对象。这就是它的样子:

public GroceryListBo updateGroceryList(GroceryListBo groceryListBo, String userId, String accessId)
{
    // some code 

    TypedQuery<GroceryList> recipeQuery = entityManager.createNamedQuery("GroceryList.findByAccessId", GroceryList.class);
    recipeQuery.setParameter(ApplicationConstants.PARAM_ACCESS_ID, identifier);
    GroceryList groceryList = recipeQuery.getSingleResult();

    BoMapper.map(groceryListBo, groceryList);

    setIdentifiersForIngredients(groceryList, userId);

    return groceryListBo;
}

private void setIdentifiersForIngredients(GroceryList groceryList, String userId)
{
    //more code

    TypedQuery<Ingredient> query = entityManager.createNamedQuery("Ingredient.findAllCaseSensitiveByUserIdAndPrefix", Ingredient.class);
    query.setParameter(ApplicationConstants.PARAM_USER_ID, userId);
    query.setParameter("ingredient", adaptedIngredient.getIngredient());
    List<Ingredient> resultList = query.getResultList(); // <- causes updateGroceryList to persist groceryList!

    //more code
}

在这个私有方法中,我在另一个表上做了一个SELECT。我需要此数据在保留之前更新groceryList属性,但SELECT查询本身会导致groceryList持久存在。这里发生了什么,我怎么能否认query.getResultList();坚持主要对象?我想知道为什么会发生这种情况,因为事务通常在主方法updateGroceryList结束时结束。

0 个答案:

没有答案
相关问题