javax.persistence.EntityManagerFactory#close ( )源码实例Demo

下面列出了javax.persistence.EntityManagerFactory#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: code   文件: JpaTest.java
@Test
public void testJpa() {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("myJpa");
    // 创建实体管理器
    EntityManager em = factory.createEntityManager();
    // 获取事务对象
    EntityTransaction tx = em.getTransaction();
    // 开启事务
    tx.begin();
    Customer customer = new Customer();
    customer.setCustName("阿里巴巴");
    // 保存操作
    em.persist(customer);
    // 提交事务
    tx.commit();
    // 释放资源
    em.close();
    factory.close();
}
 
源代码2 项目: o2oa   文件: EntityManagerContainerFactory.java
public static void close() throws Exception {
	try {
		if (instance != null) {
			for (EntityManagerFactory emf : instance.entityManagerFactoryMap.values()) {
				if (emf.isOpen()) {
					emf.close();
				}
			}
			instance.entityManagerFactoryMap.clear();
			instance.checkPersistFieldMap.clear();
			instance.checkRemoveFieldMap.clear();
		}
		/* 注销驱动程序 */
		Enumeration<Driver> drivers = DriverManager.getDrivers();
		while (drivers.hasMoreElements()) {
			Driver driver = drivers.nextElement();
			DriverManager.deregisterDriver(driver);
		}
		/* 由于可能重新载入 */
		instance = null;
	} catch (Exception e) {
		throw new Exception("close error.", e);
	}
}
 
源代码3 项目: BotLibre   文件: Migrate.java
public void migrate3() {
	Map<String, String> properties = new HashMap<String, String>();
	properties.put(PersistenceUnitProperties.JDBC_PASSWORD, Site.DATABASEPASSWORD);
	properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "fine");
	EntityManagerFactory factory = Persistence.createEntityManagerFactory("botlibre", properties);
	EntityManager em = factory.createEntityManager();
	em.getTransaction().begin();
	try {
		em.createNativeQuery("Update ChatChannel set creator_userid = (Select t2.admins_userid from CHAT_ADMINS t2 where t2.chatchannel_id = id)").executeUpdate();
		em.createNativeQuery("Update Forum set creator_userid = (Select t2.admins_userid from forum_ADMINS t2 where t2.forum_id = id)").executeUpdate();
		em.createNativeQuery("Update BotInstance set creator_userid = (Select t2.admins_userid from PANODRAINSTANCE_ADMINS t2 where t2.instances_id = id)").executeUpdate();
		em.getTransaction().commit();
	} catch (Exception exception) {
		exception.printStackTrace();
	} finally {
		if (em.getTransaction().isActive()) {
			em.getTransaction().rollback();
		}
		em.close();
		factory.close();
	}
}
 
@Test
public void test() {
    PersistenceUnitInfoImpl persistenceUnitInfo = new PersistenceUnitInfoImpl(
            LongToNumericTypeTest.class.getName(),
            Collections.singletonList( Event.class.getName() ),
            validateProperties()
    );

    Map<String, Object> configuration = new HashMap<>();
    EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
            new PersistenceUnitInfoDescriptor( persistenceUnitInfo), configuration
    );
    EntityManagerFactory emf = null;
    try {
        emf = entityManagerFactoryBuilder.build();
    }
    finally {
        if ( emf != null ) {
            emf.close();
        }
    }
}
 
源代码5 项目: java-jdbc   文件: HibernateTest.java
@Test
public void jpa_with_parent_and_active_span_only() {
  final MockSpan parent = mockTracer.buildSpan("parent").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    EntityManagerFactory entityManagerFactory = Persistence
        .createEntityManagerFactory("jpa_active_span_only");

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    entityManager.getTransaction().begin();
    entityManager.persist(new Employee());
    entityManager.persist(new Employee());
    entityManager.getTransaction().commit();
    entityManager.close();
    entityManagerFactory.close();
  }
  parent.finish();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(12, spans.size());
  checkSameTrace(spans);
  assertNull(mockTracer.activeSpan());
}
 
源代码6 项目: jasperreports   文件: EjbqlApp.java
/**
 *
 */
public void fill() throws JRException
{
	long start = System.currentTimeMillis();
	// create entity manager factory for connection with database
	EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu1", new HashMap<Object, Object>());
	EntityManager em = emf.createEntityManager();

	try
	{
		Map<String, Object> parameters = getParameters(em);
		
		JasperFillManager.fillReportToFile("build/reports/JRMDbReport.jasper", parameters);

		em.close();
		
		System.err.println("Filling time : " + (System.currentTimeMillis() - start));
	}
	finally
	{
		if (em.isOpen())
			em.close();
		if (emf.isOpen())
			emf.close();
	}
}
 
源代码7 项目: syncope   文件: DomainConfFactory.java
@Override
public void unregister(final String domain) {
    // domainKeymasterConfParamsJSON
    unregisterSingleton(domain + "KeymasterConfParamsJSON");
    unregisterBeanDefinition(domain + "KeymasterConfParamsJSON");

    // domainContentXML
    unregisterSingleton(domain + "ContentXML");
    unregisterBeanDefinition(domain + "ContentXML");

    // domainEntityManagerFactory
    try {
        EntityManagerFactory emf = ApplicationContextProvider.getBeanFactory().
                getBean(domain + "EntityManagerFactory", EntityManagerFactory.class);
        emf.close();
    } catch (Exception e) {
        LOG.error("Could not close EntityManagerFactory for Domain {}", domain, e);
    }
    unregisterSingleton(domain + "EntityManagerFactory");
    unregisterBeanDefinition(domain + "EntityManagerFactory");

    // domainTransactionManager
    unregisterSingleton(domain + "TransactionManager");
    unregisterBeanDefinition(domain + "TransactionManager");

    // domainDataSourceInitializer
    unregisterSingleton(domain.toLowerCase() + "DataSourceInitializer");

    // domainResourceDatabasePopulator
    unregisterSingleton(domain.toLowerCase() + "ResourceDatabasePopulator");

    // domainDataSource
    unregisterSingleton(domain + "DataSource");
    unregisterBeanDefinition(domain + "DataSource");
}
 
源代码8 项目: o2oa   文件: RestoreData.java
@SuppressWarnings("unchecked")
public boolean execute() throws Exception {
	List<String> containerEntityNames = new ArrayList<>();
	containerEntityNames.addAll((List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
	List<String> classNames = new ArrayList<>();
	classNames.addAll(this.catalog.keySet());
	classNames = ListTools.includesExcludesWildcard(classNames, Config.dumpRestoreData().getIncludes(),
			Config.dumpRestoreData().getExcludes());
	classNames = ListTools.includesExcludesWildcard(containerEntityNames, classNames, null);

	logger.print("find: {} data to restore, path: {}.", classNames.size(), this.dir.getAbsolutePath());
	File persistence = new File(Config.dir_local_temp_classes(), DateTools.compact(this.start) + "_dump.xml");
	PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames);
	long count = 0;
	for (int i = 0; i < classNames.size(); i++) {
		Class<JpaObject> cls = (Class<JpaObject>) Class.forName(classNames.get(i));
		EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
				persistence.getName(), PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
		if (emf != null) {
			EntityManager em = emf.createEntityManager();
			em.setFlushMode(FlushModeType.COMMIT);
			try {
				logger.print("restore data({}/{}): {}, count: {}.", (i + 1), classNames.size(), cls.getName(),
						catalog.get(cls.getName()));
				count = count + this.store(cls, em);
			} finally {
				em.close();
				emf.close();
			}
		} else {
			logger.warn("can not create 'EntityManagerFactory' for Entity:[" + cls.getName() + "]");
		}
	}
	logger.print("restore data completed, total count: {}, elapsed: {} minutes.", count,
			(System.currentTimeMillis() - start.getTime()) / 1000 / 60);
	return true;
}
 
源代码9 项目: BotLibre   文件: Migrate.java
public void migrate7() {
	Map<String, String> properties = new HashMap<String, String>();
	properties.put(PersistenceUnitProperties.JDBC_PASSWORD, Site.DATABASEPASSWORD);
	properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "fine");
	EntityManagerFactory factory = Persistence.createEntityManagerFactory(Site.PERSISTENCE_UNIT, properties);
	EntityManager em = factory.createEntityManager();
	em.getTransaction().begin();
	try {
		em.createNativeQuery("Update ChatChannel set alias = name").executeUpdate();
		em.createNativeQuery("Update Forum set alias = name").executeUpdate();
		em.createNativeQuery("Update BotInstance set alias = name").executeUpdate();
		em.createNativeQuery("Update Graphic set alias = name").executeUpdate();
		em.createNativeQuery("Update Domain set alias = name").executeUpdate();
		em.createNativeQuery("Update IssueTracker set alias = name").executeUpdate();
		em.createNativeQuery("Update Analytic set alias = name").executeUpdate();
		em.createNativeQuery("Update Script set alias = name").executeUpdate();
		em.createNativeQuery("Update Avatar set alias = name").executeUpdate();
		em.getTransaction().commit();
	} catch (Exception exception) {
		exception.printStackTrace();
	} finally {
		if (em.getTransaction().isActive()) {
			em.getTransaction().rollback();
		}
		em.close();
		factory.close();
	}
}
 
源代码10 项目: HibernateTips   文件: TestJPABootstrapping.java
@Test
public void bootstrapping() {
	log.info("... bootstrapping ...");

	EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	em.find(Book.class, 1L);

	em.getTransaction().commit();
	em.close();
	emf.close();
}
 
源代码11 项目: cuba   文件: PersistenceImpl.java
/**
 * INTERNAL.
 * Destroys the persistence configuration. Further use of this bean instance is impossible.
 */
public void dispose() {
    jpaEmf.close();
    for (String store : Stores.getAdditional()) {
        EntityManagerFactory emf = beanLocator.get("entityManagerFactory_" + store);
        emf.close();
    }
}
 
源代码12 项目: maven-framework-project   文件: SearchManager.java
public static void main(String[] args) throws Exception{
		ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
		EntityManagerFactory entityManagerFactory = applicationContext.getBean("entityManagerFactory",EntityManagerFactory.class);
		FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManagerFactory.createEntityManager());
		
		//使用Hibernate Search api查询 从多个字段匹配 name、description、authors.name
//		QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Book.class ).get();
//		Query luceneQuery = qb.keyword().onFields("name","description","authors.name").matching("移动互联网").createQuery();
		
		//使用lucene api查询 从多个字段匹配 name、description、authors.name
		//使用庖丁分词器
		MultiFieldQueryParser queryParser=new MultiFieldQueryParser(Version.LUCENE_36, new String[]{"name","description","authors.name"}, new PaodingAnalyzer());
		Query luceneQuery=queryParser.parse("实战");
		
		FullTextQuery fullTextQuery =fullTextEntityManager.createFullTextQuery(luceneQuery, Book.class);
		//设置每页显示多少条
		fullTextQuery.setMaxResults(5);
		//设置当前页
		fullTextQuery.setFirstResult(0);
		
		//高亮设置
		SimpleHTMLFormatter formatter=new SimpleHTMLFormatter("<b><font color='red'>", "<font/></b>");
		QueryScorer queryScorer=new QueryScorer(luceneQuery);
		Highlighter highlighter=new Highlighter(formatter, queryScorer);

		@SuppressWarnings("unchecked")
		List<Book> resultList = fullTextQuery.getResultList();
		
		for (Book book : resultList) {
			String highlighterString=null;
			Analyzer analyzer=new PaodingAnalyzer();
			try {
				//高亮name
				highlighterString=highlighter.getBestFragment(analyzer, "name", book.getName());
				if(highlighterString!=null){
					book.setName(highlighterString);
				}
				//高亮authors.name
				Set<Author> authors = book.getAuthors();
				for (Author author : authors) {
					highlighterString=highlighter.getBestFragment(analyzer, "authors.name", author.getName());
					if(highlighterString!=null){
						author.setName(highlighterString);
					}
				}
				//高亮description
				highlighterString=highlighter.getBestFragment(analyzer, "description", book.getDescription());
				if(highlighterString!=null){
					book.setDescription(highlighterString);
				}
			} catch (Exception e) {
			}
			
		}
		
		fullTextEntityManager.close();
		entityManagerFactory.close();
		
	}
 
源代码13 项目: o2oa   文件: DumpStorage.java
public boolean execute(String path) throws Exception {
	if (StringUtils.isEmpty(path)) {
		this.dir = new File(Config.base(), "local/dump/dumpStorage_" + DateTools.compact(this.start));
	} else {
		this.dir = new File(path);
		if (dir.getAbsolutePath().startsWith(Config.base())) {
			logger.print("path can not in base directory.");
			return false;
		}
	}
	FileUtils.forceMkdir(this.dir);
	FileUtils.cleanDirectory(this.dir);
	this.catalog = new DumpRestoreStorageCatalog();

	List<String> storageContainerEntityNames = new ArrayList<>();
	storageContainerEntityNames.addAll((List<String>) Config.resource(Config.RESOURCE_STORAGECONTAINERENTITYNAMES));
	List<String> classNames = ListTools.includesExcludesWildcard(storageContainerEntityNames,
			Config.dumpRestoreStorage().getIncludes(), Config.dumpRestoreStorage().getExcludes());
	logger.print("dump storage find {} data to dump, start at {}.", classNames.size(), DateTools.format(start));
	StorageMappings storageMappings = Config.storageMappings();
	File persistence = new File(Config.dir_local_temp_classes(), DateTools.compact(this.start) + "_dump.xml");
	PersistenceXmlHelper.write(persistence.getAbsolutePath(), classNames);
	for (int i = 0; i < classNames.size(); i++) {
		Class<StorageObject> cls = (Class<StorageObject>) Class.forName(classNames.get(i));
		EntityManagerFactory emf = OpenJPAPersistence.createEntityManagerFactory(cls.getName(),
				persistence.getName(), PersistenceXmlHelper.properties(cls.getName(), Config.slice().getEnable()));
		EntityManager em = emf.createEntityManager();
		try {
			logger.print("dump storage({}/{}): {}, estimate count: {}, estimate size: {}M.", (i + 1),
					classNames.size(), cls.getName(), this.estimateCount(em, cls),
					(this.estimateSize(em, cls) / 1024 / 1024));
			this.dump(cls, em, storageMappings);
		} finally {
			em.close();
			emf.close();
		}
	}
	FileUtils.write(new File(dir, "catalog.json"), XGsonBuilder.instance().toJson(this.catalog),
			DefaultCharset.charset);
	logger.print(
			"dump storage completed, directory: {}, count: {}, normal: {}, empty: {}, invalidStorage: {}, size: {}M, elapsed: {} minutes.",
			dir.getAbsolutePath(), this.count(), this.normal(), this.empty(), this.invalidStorage(),
			(this.size() / 1024 / 1024), (System.currentTimeMillis() - start.getTime()) / 1000 / 60);
	return true;
}
 
源代码14 项目: BotLibre   文件: DatabaseMemory.java
/**
 * Import the database into this instance.
 */
@SuppressWarnings("unchecked")
public void importMemory(String database) {
	try {
		Map<String, String> properties = new HashMap<String, String>();
		//properties.put(PersistenceUnitProperties.JDBC_DRIVER, DATABASE_DRIVER);
		properties.put(PersistenceUnitProperties.JDBC_URL, DATABASE_URL_PREFIX + database);
		//properties.put(PersistenceUnitProperties.JDBC_USER, DATABASE_USER);
		//properties.put(PersistenceUnitProperties.JDBC_PASSWORD, DATABASE_PASSWORD);
		Level debugLevel = this.bot.getDebugLevel();
		String logLevel = "INFO";
		if (debugLevel == Level.FINEST) {
			logLevel = "FINE";
		} else if (debugLevel == Level.FINE) {
			logLevel = "INFO";
		} else if (debugLevel == Level.SEVERE) {
			logLevel = "SEVER";
		} else if (debugLevel == Level.WARNING) {
			logLevel = "WARNING";
		} else if (debugLevel == Level.OFF) {
			logLevel = "OFF";
		}
		properties.put(PersistenceUnitProperties.LOGGING_LEVEL, logLevel);
		EntityManagerFactory importFactory = Persistence.createEntityManagerFactory("import", properties);
		EntityManager importEntityManager = importFactory.createEntityManager();
		Query query = importEntityManager.createQuery("Select v from Vertex v order by v.id");
		int start = 0;
		query.setFirstResult(start);
		query.setMaxResults(100);
		List<Vertex> vertices = query.getResultList();
		Map<Vertex, Vertex> identitySet = new IdentityHashMap<Vertex, Vertex>(vertices.size());
		while (!vertices.isEmpty()) {
			for (Vertex vertex : vertices) {
				getShortTermMemory().importMerge(vertex, identitySet);
			}
			save();
			start = start + 100;
			query.setFirstResult(start);
			query.setMaxResults(100);
			vertices = query.getResultList();
		}
		importFactory.close();
	} catch (RuntimeException failed) {
		this.bot.log(this, failed);
		throw failed;
	}
}
 
public void destroy(@Disposes EntityManagerFactory factory) {
    factory.close();
}
 
源代码16 项目: BotLibre   文件: Migrate.java
@SuppressWarnings("unchecked")
public void migrate2() {
	EntityManagerFactory sourceFactory = Persistence.createEntityManagerFactory("migration");
	Map<String, String> properties = new HashMap<String, String>();
	properties.put(PersistenceUnitProperties.JDBC_PASSWORD, Site.DATABASEPASSWORD);
	properties.put(PersistenceUnitProperties.DDL_GENERATION, PersistenceUnitProperties.DROP_AND_CREATE);
	properties.put(PersistenceUnitProperties.LOGGING_LEVEL, "fine");
	EntityManagerFactory targetFactory = Persistence.createEntityManagerFactory("botlibre", properties);
	EntityManager source = sourceFactory.createEntityManager();
	EntityManager target = targetFactory.createEntityManager();
	target.getTransaction().begin();
	try {
		Domain domain = new Domain(Site.DOMAIN);
		target.persist(domain);
		
		List<Tag> tags = source.createQuery("Select t from Tag t").getResultList();
		for (Tag tag : tags) {
			tag.setDomain(domain);
			target.persist(tag);
		}
		
		List<User> users = source.createQuery("Select t from User t").getResultList();
		for (User user : users) {
			if (user.getCreationDate() == null) {
				user.setCreationDate(new Date());
			}
			target.persist(user);
		}
		
		List<AvatarImage> avatars = source.createQuery("Select t from AvatarImage t").getResultList();
		for (AvatarImage avatar : avatars) {
			avatar.setDomain(domain);
			target.persist(avatar);
		}
		
		List<BotInstance> instances = source.createQuery("Select p from BotInstance p").getResultList();
		for (BotInstance instance : instances) {
			if (instance.getCreationDate() == null) {
				instance.setCreationDate(new Date());
			}
			instance.setDomain(domain);
			target.persist(instance);
		}
		
		target.getTransaction().commit();
		target.getTransaction().begin();
		Query query = target.createNativeQuery("Update Tag t set count = (Select count(p) from BotInstance p join PANODRAINSTANCE_TAGS pt on (pt.BotInstance_id = p.id) join Tag t2 on (pt.tags_id = t2.id) where p.domain_id = ? and t2.id = t.id) where t.domain_id = ?");
		query.setParameter(1, domain.getId());
		query.setParameter(2, domain.getId());
		query.executeUpdate();
		query = target.createQuery("Delete from Tag t where t.count = 0 and t.domain = :domain");
		query.setParameter("domain", domain);
		query.executeUpdate();
		target.getTransaction().commit();
		
	} catch (Exception exception) {
		exception.printStackTrace();
	} finally {
		if (target.getTransaction().isActive()) {
			target.getTransaction().rollback();
		}
		source.close();
		target.close();
		sourceFactory.close();
		targetFactory.close();
	}
}
 
public void close(@Disposes EntityManagerFactory entityManagerFactory) {
    entityManagerFactory.close();
}
 
@Test
public void testIdPersistence(){

    EntityManagerFactory factory = Persistence.createEntityManagerFactory("DB");//same name as in persistence.xml
    EntityManager em = factory.createEntityManager();//it works as a cache/buffer until we commit a transaction

    User01 user01 = new User01();
    user01.setName("AName");
    user01.setSurname("ASurname");

    // by default, no id, until data committed to the database
    assertNull(user01.getId());

    //committing data to database needs to be inside a transaction
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try{
        /*
            The following is actually executing this SQL statement:

            insert into User01 (name, surname, id) values (?, ?, ?)

         */
        em.persist(user01);

        //there can be several operations on the "cache" EntityManager before we actually commit the transaction
        tx.commit();
    } catch (Exception e){
        //abort the transaction if there was any exception
        tx.rollback();
        fail();//fail the test
    } finally {
        //in any case, make sure to close the opened resources
        em.close();
        factory.close();
    }

    //id should have now be set
    assertNotNull(user01.getId());
    System.out.println("GENERATED ID: "+user01.getId());
}
 
public void destroy(@Disposes EntityManagerFactory factory) {
    factory.close();
}
 
public void destroy(@Disposes EntityManagerFactory factory) {
    factory.close();
}