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

The following examples show how to use javax.persistence.EntityManager#flush() . 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: MCRCategoryDAOImpl.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private static <T> T withoutFlush(EntityManager entityManager, boolean flushAtEnd,
    Function<EntityManager, T> task) {
    FlushModeType fm = entityManager.getFlushMode();
    entityManager.setFlushMode(FlushModeType.COMMIT);
    try {
        T result = task.apply(entityManager);
        if (flushAtEnd) {
            entityManager.flush();
        }
        return result;
    } catch (RuntimeException e) {
        throw e;
    } finally {
        entityManager.setFlushMode(fm);
    }
}
 
Example 2
Source File: MessageDao.java    From peer-os with Apache License 2.0 6 votes vote down vote up
@Override
public void persist( final MessageEntity item )
{
    EntityManager em = emf.createEntityManager();
    try
    {
        em.getTransaction().begin();
        em.persist( item );
        em.flush();
        em.getTransaction().commit();
    }
    catch ( Exception e )
    {
        LOG.error( e.toString(), e );
        if ( em.getTransaction().isActive() )
        {
            em.getTransaction().rollback();
        }
    }
    finally
    {
        em.close();
    }
}
 
Example 3
Source File: JpaWorkspaceActivityDao.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Transactional
void doUpdate(boolean optional, String workspaceId, Consumer<WorkspaceActivity> updater) {
  EntityManager em = managerProvider.get();
  WorkspaceActivity activity = em.find(WorkspaceActivity.class, workspaceId);
  if (activity == null) {
    if (optional) {
      return;
    }
    activity = new WorkspaceActivity();
    activity.setWorkspaceId(workspaceId);

    updater.accept(activity);

    em.persist(activity);
  } else {
    updater.accept(activity);

    em.merge(activity);
  }

  em.flush();
}
 
Example 4
Source File: BaseDaoImpl.java    From metacat with Apache License 2.0 6 votes vote down vote up
@Override
public T save(final T entity, final boolean flush) {
    T result = null;
    final EntityManager entityManager = em.get();
    if (isNew(entity)) {
        entityManager.persist(entity);
        result = entity;
    } else {
        result = entityManager.merge(entity);
    }
    if (flush) {
        entityManager.flush();
    }

    return result;
}
 
Example 5
Source File: HibernatePluginTest.java    From HotswapAgent with GNU General Public License v2.0 6 votes vote down vote up
private void doInTransaction(InTransaction inTransaction) throws Exception {
    System.out.println(entityManagerFactory);
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();

    try {
        TestEntity simpleEntity = new TestEntity("Test", "descr");
        entityManager.persist(simpleEntity);

        // flush and clear persistence context
        entityManager.flush();
        entityManager.clear();

        inTransaction.process(entityManager);
    } finally {
        entityManager.getTransaction().rollback();
        entityManager.close();
    }
}
 
Example 6
Source File: AbstractJpaTest.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
public static void clear(final EntityManager em, JpaQueryFactory factory) {
	factory.initalize(new JpaQueryFactoryContext(){
		@Override
		public EntityManager getEntityManager() {
			return em;
		}

		@Override
		public MetaLookup getMetaLookup() {
			MetaLookup metaLookup = new MetaLookup();
			metaLookup.addProvider(new JpaMetaProvider());
			return metaLookup;
		}});
	clear(em, factory.query(TestSubclassWithSuperclassPk.class).buildExecutor().getResultList());
	clear(em, factory.query(RelatedEntity.class).buildExecutor().getResultList());
	clear(em, factory.query(TestEntity.class).buildExecutor().getResultList());
	clear(em, factory.query(OtherRelatedEntity.class).buildExecutor().getResultList());
	em.flush();
	em.clear();
}
 
Example 7
Source File: ContainerMetricsDAO.java    From peer-os with Apache License 2.0 6 votes vote down vote up
void persist( ContainerMetrics item )
{
    EntityManager em = daoManager.getEntityManagerFromFactory();
    try
    {
        daoManager.startTransaction( em );

        em.persist( item );
        em.flush();

        daoManager.commitTransaction( em );
    }
    catch ( Exception e )
    {
        daoManager.rollBackTransaction( em );

        LOG.error( e.getMessage() );
    }
    finally
    {
        daoManager.closeEntityManager( em );
    }
}
 
Example 8
Source File: JpaInviteDao.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Transactional
protected void doRemove(String domain, String instance, String email) {
  try {
    InviteImpl invite = getEntity(domain, instance, email);
    final EntityManager manager = managerProvider.get();
    manager.remove(invite);
    manager.flush();
  } catch (NotFoundException e) {
    // invite is already removed
  }
}
 
Example 9
Source File: BadgeSkillResourceIntTest.java    From TeamDojo with Apache License 2.0 5 votes vote down vote up
/**
 * Create an entity for this test.
 * <p>
 * This is a static method, as tests for other entities might also need it,
 * if they test an entity which requires the current entity.
 */
public static BadgeSkill createEntity(EntityManager em) {
    BadgeSkill badgeSkill = new BadgeSkill();
    // Add required entity
    Badge badge = BadgeResourceIntTest.createEntity(em);
    em.persist(badge);
    em.flush();
    badgeSkill.setBadge(badge);
    // Add required entity
    Skill skill = SkillResourceIntTest.createEntity(em);
    em.persist(skill);
    em.flush();
    badgeSkill.setSkill(skill);
    return badgeSkill;
}
 
Example 10
Source File: JpaPreferenceDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional
protected void doSetPreference(PreferenceEntity prefs) {
  final EntityManager manager = managerProvider.get();
  final PreferenceEntity existing = manager.find(PreferenceEntity.class, prefs.getUserId());
  if (existing != null) {
    manager.merge(prefs);
  } else {
    manager.persist(prefs);
  }
  manager.flush();
}
 
Example 11
Source File: ApplicationManagedEntityManagerIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected void doInstantiateAndSave(EntityManager em) {
	testStateClean();
	Person p = new Person();

	p.setFirstName("Tony");
	p.setLastName("Blair");
	em.persist(p);

	em.flush();
	assertEquals("1 row must have been inserted", 1, countRowsInTable(em, "person"));
}
 
Example 12
Source File: LeaveJpaEntityTest.java    From activiti-in-action-codes with Apache License 2.0 5 votes vote down vote up
@Deployment(resources = "chapter17/leave-jpa.bpmn")
public void testSaveEntity() {
    LeaveJpaEntity leave = new LeaveJpaEntity();
    leave.setReason("测试");
    EntityManager manager = entityManagerFactory.createEntityManager();
    manager.getTransaction().begin();

    manager.persist(leave);

    manager.flush();
    manager.getTransaction().commit();
    manager.close();
}
 
Example 13
Source File: KradEclipseLinkCustomizerTest.java    From rice with Educational Community License v2.0 5 votes vote down vote up
@Test
public void testQueryCustomizerValueClass() throws Exception {
    EntityManagerFactory factory = (EntityManagerFactory) context.getBean("entityManagerFactory");
    assertNotNull(factory);

    TestEntity8 testEntity1 = new TestEntity8();
    testEntity1.setName("MyAwesomeTestEntity1");

    TestRelatedExtension extension = new TestRelatedExtension();
    extension.setAccountTypeCode("NM");

    EntityManager entityManager = factory.createEntityManager();

    try {
        testEntity1 = new TestEntity8();
        testEntity1.setName("MyCustomFilter");
        entityManager.persist(testEntity1);
        extension.setNumber(testEntity1.getNumber());
        entityManager.persist(extension);
        entityManager.flush();
    } finally {
        entityManager.close();
    }

    //Now confirm that the entity fetch found travel extension
    try {
        entityManager = factory.createEntityManager();
        testEntity1 = entityManager.find(TestEntity8.class, testEntity1.getNumber());
        assertTrue("Matched found for base entity", testEntity1 != null && StringUtils.equals("MyCustomFilter",
                testEntity1.getName()));
        assertTrue("Matching travel extension", testEntity1.getAccountExtension() == null);
    } finally {
        entityManager.close();
    }

}
 
Example 14
Source File: BaseDao.java    From ranger with Apache License 2.0 5 votes vote down vote up
public void commitTransaction() {
	EntityManager em = getEntityManager();

	if(em != null) {
		em.flush();

		EntityTransaction et = em.getTransaction();

		if(et != null) {
			et.commit();
		}
	}
}
 
Example 15
Source File: JPAVariableTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void setupIllegalJPAEntities() {
  EntityManager manager = entityManagerFactory.createEntityManager();
  manager.getTransaction().begin();

  compoundIdJPAEntity = new CompoundIdJPAEntity();
  EmbeddableCompoundId id = new EmbeddableCompoundId();
  id.setIdPart1(123L);
  id.setIdPart2("part2");
  compoundIdJPAEntity.setId(id);
  manager.persist(compoundIdJPAEntity);

  manager.flush();
  manager.getTransaction().commit();
  manager.close();
}
 
Example 16
Source File: JpaAccountDao.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Transactional
protected void doUpdate(AccountImpl update) throws NotFoundException {
  final EntityManager manager = managerProvider.get();
  final AccountImpl account = manager.find(AccountImpl.class, update.getId());
  if (account == null) {
    throw new NotFoundException(
        format("Couldn't update account with id '%s' because it doesn't exist", update.getId()));
  }
  manager.merge(update);
  manager.flush();
}
 
Example 17
Source File: JPAVariableTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void setupIllegalJPAEntities() {
  EntityManager manager = entityManagerFactory.createEntityManager();
  manager.getTransaction().begin();

  compoundIdJPAEntity = new CompoundIdJPAEntity();
  EmbeddableCompoundId id = new EmbeddableCompoundId();
  id.setIdPart1(123L);
  id.setIdPart2("part2");
  compoundIdJPAEntity.setId(id);
  manager.persist(compoundIdJPAEntity);

  manager.flush();
  manager.getTransaction().commit();
  manager.close();
}
 
Example 18
Source File: JpaUtil.java    From linq with Apache License 2.0 4 votes vote down vote up
/**
 * 刷新实体对象对应的EntityManager
 * @param entity 实体对象
 * @param <T> 领域类(实体类)范型
 */
public static <T> void flush(T entity) {
	Assert.notNull(entity, "entity can not be null.");
	EntityManager em = getEntityManager(entity.getClass());
	em.flush();
}
 
Example 19
Source File: TestConflictedChangeFile.java    From desktop with GNU General Public License v3.0 4 votes vote down vote up
public static void doProcess(String fileName) throws Exception{
    Folder root = staticFunctionsTest.initConfig(config);
    EntityManager em = config.getDatabase().getEntityManager();
    
    //create v1 ACK
    File f1 = staticFunctionsTest.createFile(root.getLocalFile().getPath() + fileName, "content1");
    CloneFile dbFile = staticFunctionsTest.indexNewRequest(root, f1, null);
    
    dbFile.setSyncStatus(SyncStatus.UPTODATE);
    dbFile.setServerUploadedAck(true);
    dbFile.setServerUploadedTime(new Date());
    
    dbFile.merge();
            
    //create v2
    f1 = staticFunctionsTest.createFile(root.getLocalFile().getPath() + fileName, "content2");
    dbFile = staticFunctionsTest.indexNewRequest(root, f1, dbFile);       
            
    //create v3
    f1 = staticFunctionsTest.createFile(root.getLocalFile().getPath() + fileName, "content3");
    dbFile = staticFunctionsTest.indexNewRequest(root, f1, dbFile); 
    
    //create v4
    f1 = staticFunctionsTest.createFile(root.getLocalFile().getPath() + fileName, "content4");
    dbFile = staticFunctionsTest.indexNewRequest(root, f1, dbFile);
    
    //create v5
    f1 = staticFunctionsTest.createFile(root.getLocalFile().getPath() + fileName, "content5");        
    staticFunctionsTest.indexNewRequest(root, f1, dbFile);
    
    //remove v5        
    em.getTransaction().begin();
    dbFile = db.getFile(root, f1);
    
    Object toBeRemoved = em.merge(dbFile);
    em.remove(toBeRemoved);
    
    em.flush();
    em.getTransaction().commit();
    
    staticFunctionsTest.createFile(root.getLocalFile().getPath() + fileName, "content4");
    //create a conflicted modification v2
    /*Update update = Update.parse(dbFile);        
    update.setVersion(2);
    update.setServerUploadedAck(true);
    update.setServerUploadedTime(new Date());  
    
    List<Update> list = new ArrayList<Update>();
    list.add(update);
    
    Profile profile = config.getProfile();
    ChangeManager cm = profile.getRemoteWatcher().getChangeManager();        
    cm.queueUpdates(list);
    
    System.out.println("FINISH!!!!\n\n");        
    System.out.println("The result is: \n file1 with content5. \n file1 conflicted with content4. \n 5 rows in database File1 New ACK, Changed ACK | File1 conflicted New, Changed, Changed.");
    while(true) { }*/
}
 
Example 20
Source File: JpaProfileDao.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Transactional
protected void doCreate(ProfileImpl profile) {
  EntityManager manager = managerProvider.get();
  manager.persist(profile);
  manager.flush();
}