Java Code Examples for javax.persistence.EntityManager#refresh()

The following examples show how to use javax.persistence.EntityManager#refresh() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UpdateDao.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public void persist( final UpdateEntity item )
{
    EntityManager em = emf.createEntityManager();
    try
    {
        em.getTransaction().begin();
        em.persist( item );
        em.flush();
        em.refresh( item );
        em.getTransaction().commit();
    }
    catch ( Exception e )
    {
        LOG.error( e.toString(), e );
        if ( em.getTransaction().isActive() )
        {
            em.getTransaction().rollback();
        }
    }
    finally
    {
        em.close();
    }
}
 
Example 2
Source File: RESTApiFacadeImpl.java    From zstack with Apache License 2.0 6 votes vote down vote up
private RestAPIVO persist(APIMessage msg) {
    RestAPIVO vo = new RestAPIVO();
    vo.setUuid(msg.getId());
    vo.setApiMessageName(msg.getMessageName());
    vo.setState(RestAPIState.Processing);
    EntityManager mgr = getEntityManager();
    EntityTransaction tran = mgr.getTransaction();
    try {
        tran.begin();
        mgr.persist(vo);
        mgr.flush();
        mgr.refresh(vo);
        tran.commit();
        return vo;
    } catch (Exception e) {
        ExceptionDSL.exceptionSafe(tran::rollback);
        throw new CloudRuntimeException(e);
    } finally {
        ExceptionDSL.exceptionSafe(mgr::close);
    }
}
 
Example 3
Source File: JpaProfileDao.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
@Transactional
public ProfileImpl getById(String userId) throws NotFoundException, ServerException {
  requireNonNull(userId, "Required non-null id");
  try {
    final EntityManager manager = managerProvider.get();
    final ProfileImpl profile = manager.find(ProfileImpl.class, userId);
    if (profile == null) {
      throw new NotFoundException(format("Couldn't find profile for user with id '%s'", userId));
    }
    manager.refresh(profile);
    return profile;
  } catch (RuntimeException x) {
    throw new ServerException(x.getLocalizedMessage(), x);
  }
}
 
Example 4
Source File: OptimisticLockingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test(expected = OptimisticLockException.class)
public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
    EntityManager em = getEntityManagerWithOpenTransaction();
    OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
    em.refresh(student, LockModeType.OPTIMISTIC);

    EntityManager em2 = getEntityManagerWithOpenTransaction();
    OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
    em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
    student2.setName("RICHARD");
    em2.persist(student2);
    em2.getTransaction()
        .commit();
    em2.close();

    student.setName("JOHN");
    em.persist(student);
    em.getTransaction()
        .commit();
    em.close();
}
 
Example 5
Source File: EntityManagerHelper.java    From testgrid with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the refreshed result list.
 *
 * @param entityManager Entity Manager object
 * @param resultList    Result List of query execution
 * @return List of refreshed results
 */
public static <T> List<T> refreshResultList(EntityManager entityManager, List<T> resultList) {
    if (!resultList.isEmpty()) {
        for (T entity : resultList) {
            entityManager.refresh(entity);
        }
    }
    return resultList;
}
 
Example 6
Source File: MCRCategoryDAOImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void deleteCategory(MCRCategoryID id) {
    EntityManager entityManager = MCREntityManagerProvider.getCurrentEntityManager();
    LOGGER.debug("Will get: {}", id);
    MCRCategoryImpl category = getByNaturalID(entityManager, id);
    try {
        entityManager.refresh(category); //for MCR-1863
    } catch (EntityNotFoundException e) {
        //required since hibernate 5.3 if category is deleted within same transaction.
        //junit: testLicenses()
    }
    if (category == null) {
        throw new MCRPersistenceException("Category " + id + " was not found. Delete aborted.");
    }
    LOGGER.debug("Will delete: {}", category.getId());
    MCRCategory parent = category.parent;
    category.detachFromParent();
    entityManager.remove(category);
    if (parent != null) {
        entityManager.flush();
        LOGGER.debug("Left: {} Right: {}", category.getLeft(), category.getRight());
        // always add +1 for the currentNode
        int nodes = 1 + (category.getRight() - category.getLeft()) / 2;
        final int increment = nodes * -2;
        // decrement left and right values by nodes
        updateLeftRightValue(entityManager, category.getRootID(), category.getLeft(), increment);
    }
    updateTimeStamp();
    updateLastModified(category.getRootID());
}
 
Example 7
Source File: JpaUtils.java    From jdal with Apache License 2.0 5 votes vote down vote up
/** 
 * Initialize entity attribute
 * @param em
 * @param entity
 * @param a
 * @param depth
 */
@SuppressWarnings("rawtypes")
private static void intialize(EntityManager em, Object entity, Object attached, Attribute a, int depth) {
	Object value = PropertyAccessorFactory.forDirectFieldAccess(attached).getPropertyValue(a.getName());
	if (!em.getEntityManagerFactory().getPersistenceUnitUtil().isLoaded(value)) {
		em.refresh(value);
	}
	
	PropertyAccessorFactory.forDirectFieldAccess(entity).setPropertyValue(a.getName(), value);
	
	initialize(em, value, depth - 1);
}
 
Example 8
Source File: SharedEntityManagerCreatorTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test(expected = TransactionRequiredException.class)
public void transactionRequiredExceptionOnRefresh() {
	EntityManagerFactory emf = mock(EntityManagerFactory.class);
	EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
	em.refresh(new Object());
}
 
Example 9
Source File: SharedEntityManagerCreatorTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test(expected = TransactionRequiredException.class)
public void transactionRequiredExceptionOnRefresh() {
	EntityManagerFactory emf = mock(EntityManagerFactory.class);
	EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
	em.refresh(new Object());
}
 
Example 10
Source File: SharedEntityManagerCreatorTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test(expected = TransactionRequiredException.class)
public void transactionRequiredExceptionOnRefresh() {
	EntityManagerFactory emf = mock(EntityManagerFactory.class);
	EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
	em.refresh(new Object());
}
 
Example 11
Source File: EntityManagerHelper.java    From testgrid with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the refreshed result.
 *
 * @param entityManager Entity Manager object
 * @param result        Result of query execution
 * @return Refreshed result
 */
public static <T> T refreshResult(EntityManager entityManager, T result) {
    entityManager.refresh(result);
    return result;
}