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

The following examples show how to use javax.persistence.EntityManager#clear() . 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: DumpData.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private <T> void dump(Class<T> cls, EntityManager em) throws Exception {
	/** 创建最终存储文件的目录 */
	File directory = new File(dir, cls.getName());
	FileUtils.forceMkdir(directory);
	FileUtils.cleanDirectory(directory);
	int count = 0;
	int size = Config.dumpRestoreData().getBatchSize();
	String id = "";
	List<T> list = null;
	do {
		list = this.list(em, cls, id, size);
		if (ListTools.isNotEmpty(list)) {
			count = count + list.size();
			id = BeanUtils.getProperty(list.get(list.size() - 1), JpaObject.id_FIELDNAME);
			File file = new File(directory, count + ".json");
			FileUtils.write(file, pureGsonDateFormated.toJson(list), DefaultCharset.charset);
		}
		em.clear();
		Runtime.getRuntime().gc();
	} while (ListTools.isNotEmpty(list));
	this.catalog.put(cls.getName(), count);
}
 
Example 2
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 3
Source File: AbstractOperationsTest.java    From crnk-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 MetaPartition getMetaPartition() {
			MetaLookupImpl metaLookup = new MetaLookupImpl();
			JpaMetaProvider metaProvider = new JpaMetaProvider(em.getEntityManagerFactory());
			metaLookup.addProvider(metaProvider);
			metaLookup.initialize();
			return metaProvider.getPartition();
		}

		@Override
		public EntityManager getEntityManager() {
			return em;
		}
	});
	clear(em, factory.query(MovieEntity.class).buildExecutor().getResultList());
	clear(em, factory.query(PersonEntity.class).buildExecutor().getResultList());
	em.flush();
	em.clear();
}
 
Example 4
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 {
    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 5
Source File: MultipleExecutorsIt.java    From database-rider with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLoadUsersFromJsonDataset() {
    for (DataSetExecutorImpl executor : executors) {
        DataSetConfig DataSetConfig = new DataSetConfig("datasets/json/users.json");
        executor.createDataSet(DataSetConfig);
        EntityManager em = instance(executor.getExecutorId() + "-pu").em();
        em.clear();
        User user = (User) em.createQuery("select u from User u left join fetch u.followers where u.id = 1").getSingleResult();
        assertThat(user).isNotNull();
        assertThat(user.getId()).isEqualTo(1);
        assertThat(user.getTweets()).hasSize(1);
        Assert.assertEquals("dbunit rules json example", user.getTweets().get(0).getContent());
        assertThat(user.getFollowers()).isNotNull().hasSize(1);
        Follower expectedFollower = new Follower(2,1);
        assertThat(user.getFollowers()).contains(expectedFollower);
    }

}
 
Example 6
Source File: DbAuditProvider.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void clearEntityManager() {
	try {
		EntityManager em = getEntityManager();
		
		if(em != null) {
			em.clear();
		}
	} catch(Exception excp) {
		LOG.warn("DbAuditProvider.clearEntityManager(): failed", excp);
	}
}
 
Example 7
Source File: EntityManagerTest.java    From hyperjaxb3 with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void save(A a) {
	final EntityManager em = createEntityManager();
	em.getTransaction().begin();
	em.merge(a);
	em.getTransaction().commit();
	em.clear();
	em.close();
}
 
Example 8
Source File: EntityManagerProducerProxyTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testProduceEntityManagerMultipleTimesBakedByHolder() {
    // GIVEN
    final EntityManager em = mock(EntityManager.class);
    EntityManagerHolder.INSTANCE.setEntityManager(em);
    final EntityManagerProducerProxy producer = new EntityManagerProducerProxy(delegate);

    // WHEN
    final EntityManager instance1 = producer.produce(context);
    final EntityManager instance2 = producer.produce(context);

    // THEN (only proxies are created)
    assertThat(instance1, not(nullValue()));
    assertThat(instance2, not(nullValue()));
    assertThat(instance2, not(equalTo(instance1)));

    // WHEN (methods are invoked on the proxies)
    instance1.clear();
    instance2.clear();

    // THEN (the actual instance is retrieved from the holder and used)
    verify(em, times(2)).clear();

    // WHEN (further method is invoked on the proxies)
    instance1.close();
    instance2.close();

    // THEN (previously retrieved instance used)
    verify(em, times(2)).close();

    // WHEN
    producer.dispose(instance1);
    producer.dispose(instance2);

    // THEN (nothing happens since the instance is managed by the test environment)
    verifyNoMoreInteractions(delegate);
}
 
Example 9
Source File: EntityManagerProducerProxyTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testProduceAndUseEntityManagerHavingAnInstanceBackedByTheHolder() {
    // GIVEN
    final EntityManager em = mock(EntityManager.class);
    EntityManagerHolder.INSTANCE.setEntityManager(em);
    final EntityManagerProducerProxy producer = new EntityManagerProducerProxy(delegate);

    // WHEN
    final EntityManager instance = producer.produce(context);

    // THEN (only a proxy is created)
    assertThat(instance, not(nullValue()));
    verifyNoMoreInteractions(delegate);

    // WHEN (method is invoked on the proxy)
    instance.clear();

    // THEN (the actual instance is retrieved from the holder and used)
    verifyNoMoreInteractions(delegate);
    verify(em).clear();

    // WHEN (further method is invoked on the proxy)
    instance.close();

    // THEN (previously retrieved instance used)
    verifyNoMoreInteractions(delegate);
    verify(em).close();

    // WHEN
    producer.dispose(instance);

    // THEN (nothing happens since the instance is managed by the test environment)
    verifyNoMoreInteractions(delegate);
}
 
Example 10
Source File: EntityManagerProducerProxyTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testProduceAndUseEntityManagerWithoutHavingAnInstanceBackedByTheHolder() {
    // GIVEN
    final EntityManagerProducerProxy producer = new EntityManagerProducerProxy(delegate);

    // WHEN
    final EntityManager instance = producer.produce(context);

    // THEN (only a proxy is created)
    assertThat(instance, not(nullValue()));
    verifyNoMoreInteractions(delegate);

    // WHEN (method is invoked on the proxy)
    instance.clear();

    // THEN (the actual instance is created and used)
    verify(delegate).produce(context);
    verify(producedEntityManagers.get(0)).clear();

    // WHEN (further method is invoked on the proxy)
    instance.close();

    // THEN (previously created instance used)
    verifyNoMoreInteractions(delegate);
    verify(producedEntityManagers.get(0)).close();

    // WHEN
    producer.dispose(instance);

    // THEN (delegate.dispose is called for it)
    verify(delegate).dispose(producedEntityManagers.get(0));
    verifyNoMoreInteractions(delegate);
}
 
Example 11
Source File: DBAuditDestination.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void clearEntityManager() {
	try {
		EntityManager em = getEntityManager();

		if (em != null) {
			em.clear();
		}
	} catch (Exception excp) {
		logger.warn("DBAuditDestination.clearEntityManager(): failed", excp);
	}
}
 
Example 12
Source File: AbstractDatabaseTest.java    From jadira with Apache License 2.0 5 votes vote down vote up
protected <E extends Serializable> E persist(E item) {
    EntityManager manager = factory.createEntityManager();
    manager.getTransaction().begin();
    manager.persist(item);
    manager.getTransaction().commit();

    manager.clear();

    manager.close();

    return item;
}
 
Example 13
Source File: AbstractDatabaseTest.java    From jadira with Apache License 2.0 5 votes vote down vote up
protected void verifyDatabaseTable() {
    EntityManager manager = factory.createEntityManager();
    verifyDatabaseTable(manager, tableType.getAnnotation(Table.class).name());

    manager.clear();

    manager.close();
}
 
Example 14
Source File: MultipleExecutorsIt.java    From database-rider with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSeedUserDataSet() {
    for (DataSetExecutorImpl executor : executors) {
        DataSetConfig DataSetConfig = new DataSetConfig("datasets/yml/users.yml").
            useSequenceFiltering(true);
        executor.createDataSet(DataSetConfig);
        EntityManager em = instance(executor.getExecutorId() + "-pu").em();
        em.clear();//jpa cache
        User user = (User) em.createQuery("select u from User u where u.id = 1").getSingleResult();
        assertThat(user).isNotNull();
        assertThat(user.getId()).isEqualTo(1);
    }

}
 
Example 15
Source File: AbstractJpaTest.java    From crnk-framework with Apache License 2.0 5 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 MetaPartition getMetaPartition() {
            JpaMetaProvider jpaMetaProvider = new JpaMetaProvider(em.getEntityManagerFactory());
            MetaLookupImpl metaLookup = new MetaLookupImpl();
            metaLookup.addProvider(jpaMetaProvider);
            metaLookup.initialize();
            return jpaMetaProvider.getPartition();
        }
    });
    clear(em, factory.query(OneToOneTestEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(OneToOneOppositeEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(ManyToManyTestEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(ManyToManyOppositeEntity.class).buildExecutor().getResultList());
    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());
    clear(em, factory.query(CountryTranslationEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(CountryEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(LangEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(BasicAttributesTestEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(RenamedTestEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(UuidTestEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(JpaTransientTestEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(CustomTypeTestEntity.class).buildExecutor().getResultList());
    clear(em, factory.query(OverrideIdTestEntity.class).buildExecutor().getResultList());
    em.flush();
    em.clear();
}
 
Example 16
Source File: RestoreData.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private <T> long store(Class<T> cls, EntityManager em) throws Exception {
	File directory = new File(this.dir, cls.getName());
	if ((!directory.exists()) || (!directory.isDirectory())) {
		throw new Exception("can not find directory: " + directory.getAbsolutePath() + ".");
	}
	long count = 0;
	List<File> files = new ArrayList<>(FileUtils.listFiles(directory, new String[] { "json" }, false));
	/** 对文件进行排序,和dump的时候的顺序保持一直 */
	Collections.sort(files, new Comparator<File>() {
		public int compare(File o1, File o2) {
			String n1 = FilenameUtils.getBaseName(o1.getName());
			String n2 = FilenameUtils.getBaseName(o2.getName());
			Integer i1 = Integer.parseInt(n1);
			Integer i2 = Integer.parseInt(n2);
			return i1.compareTo(i2);
		}
	});
	/** 尽量在最后进行清空操作 */
	this.clean(cls, em);
	File file = null;
	for (int i = 0; i < files.size(); i++) {
		file = files.get(i);
		System.out.println("restoring " + (i + 1) + "/" + files.size() + " part of data: " + cls.getName() + ".");
		JsonArray raws = this.convert(file);
		em.getTransaction().begin();
		for (JsonElement o : raws) {
			T t = pureGsonDateFormated.fromJson(o, cls);
			em.persist(t);
			count++;
		}
		em.getTransaction().commit();
		em.clear();
		Runtime.getRuntime().gc();
	}
	System.out.println("restore data: " + cls.getName() + " completed, count: " + count + ".");
	return count;

}
 
Example 17
Source File: MCRIFSCommands.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
@MCRCommand(syntax = "generate md5sum files in directory {0}",
    help = "writes md5sum files for every content store in directory {0}")
public static void writeMD5SumFile(String targetDirectory) throws IOException {
    File targetDir = getDirectory(targetDirectory);
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    MCRStreamQuery<MCRFSNODES> streamQuery = MCRStreamQuery.getInstance(em,
        "from MCRFSNODES where type='F' order by storeid, storageid", MCRFSNODES.class);
    Map<String, MCRContentStore> availableStores = MCRContentStoreFactory.getAvailableStores();
    String currentStoreId = null;
    MCRContentStore currentStore = null;
    File currentStoreBaseDir = null;
    BufferedWriter bw = null;
    String nameOfProject = MCRConfiguration2.getString("MCR.NameOfProject").orElse("MyCoRe");
    try {
        Iterator<MCRFSNODES> fsnodes = streamQuery.getResultStream().iterator();
        while (fsnodes.hasNext()) {
            MCRFSNODES fsNode = fsnodes.next();
            String storeID = fsNode.getStoreid();
            String storageID = fsNode.getStorageid();
            String md5 = fsNode.getMd5();
            em.detach(fsNode);
            if (!storeID.equals(currentStoreId)) {
                //initialize current store
                currentStoreId = storeID;
                currentStore = availableStores.get(storeID);
                if (bw != null) {
                    bw.close();
                }
                File outputFile = new File(targetDir,
                    new MessageFormat("{0}-{1}.md5", Locale.ROOT).format(new Object[] { nameOfProject, storeID }));
                LOGGER.info("Writing to file: {}", outputFile.getAbsolutePath());
                bw = Files.newBufferedWriter(outputFile.toPath(), Charset.defaultCharset(),
                    StandardOpenOption.CREATE);
                try {
                    currentStoreBaseDir = currentStore.getBaseDir();
                } catch (Exception e) {
                    LOGGER.warn("Could not get baseDir of store: {}", storeID, e);
                    currentStoreBaseDir = null;
                }
            }
            String path = currentStoreBaseDir != null ? currentStore.getLocalFile(storageID).getAbsolutePath()
                : storageID;
            //current store initialized
            String line = new MessageFormat("{0}  {1}\n", Locale.ROOT).format(new Object[] { md5, path });
            bw.write(line);
        }
    } finally {
        if (bw != null) {
            try {
                bw.close();
            } catch (IOException e1) {
                LOGGER.warn("Error while closing file.", e1);
            }
        }
        em.clear();
    }
}
 
Example 18
Source File: MyProvider.java    From incubator-batchee with Apache License 2.0 4 votes vote down vote up
@Override
public void release(final EntityManager em) {
    em.clear();
    em.close();
}
 
Example 19
Source File: SoapboxDao.java    From soapbox-race with GNU General Public License v2.0 4 votes vote down vote up
public ISoapBoxEntity findById(Class<? extends ISoapBoxEntity> entityClass, Long id) {
	EntityManager manager = ConnectionDB.getManager();
	manager.clear();
	return manager.find(entityClass, id);
}
 
Example 20
Source File: RestoreStorage.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
private <T extends StorageObject> long store(final Class<T> cls, final EntityManager em,
		final StorageMappings storageMappings) throws Exception {
	final File classDirectory = new File(this.dir, cls.getName());
	if ((!classDirectory.exists()) || (!classDirectory.isDirectory())) {
		throw new Exception("can not find directory: " + classDirectory.getAbsolutePath() + ".");
	}
	long count = 0;
	final List<File> files = new ArrayList<File>(
			FileUtils.listFiles(classDirectory, new String[] { "json" }, false));
	/** 对文件进行排序,和dump的时候的顺序保持一直 */
	Collections.sort(files, new Comparator<File>() {
		public int compare(final File o1, final File o2) {
			final String n1 = FilenameUtils.getBaseName(o1.getName());
			final String n2 = FilenameUtils.getBaseName(o2.getName());
			final Integer i1 = Integer.parseInt(n1);
			final Integer i2 = Integer.parseInt(n2);
			return i1.compareTo(i2);
		}
	});
	/** 尽量将删除的工作放在后面 */
	this.clean(cls, em, storageMappings);
	StorageMapping mapping = null;
	File file = null;
	for (int i = 0; i < files.size(); i++) {
		file = files.get(i);
		/** 必须先转换成 jsonElement 不能直接转成泛型T,如果直接转会有类型不匹配比如Integer变成了Double */
		logger.print("restoring " + (i + 1) + "/" + files.size() + " part of storage: " + cls.getName() + ".");
		final JsonArray raws = this.convert(file);
		if (null != raws) {
			em.getTransaction().begin();
			for (final JsonElement o : raws) {
				final T t = pureGsonDateFormated.fromJson(o, cls);
				if (Config.dumpRestoreStorage().getRedistribute()) {
					mapping = storageMappings.random(cls);
				} else {
					mapping = storageMappings.get(cls, t.getStorage());
				}
				if (null == mapping) {
					throw new Exception(
							"can not find storageMapping class: " + cls.getName() + ", name:" + t.getName());
				}
				final File source = new File(classDirectory, FilenameUtils.getBaseName(file.getName())
						+ StorageObject.PATHSEPARATOR + FilenameUtils.getName(t.path()));
				try (FileInputStream input = new FileInputStream(source)) {
					t.saveContent(mapping, input, t.getName());
				}
				em.persist(t);
				count++;
			}
			em.getTransaction().commit();
			em.clear();
			Runtime.getRuntime().gc();
		}
	}
	return count;
}