Java Code Examples for javax.persistence.EntityManagerFactory.close()

The following are Jave code examples for showing how to use close() of the javax.persistence.EntityManagerFactory class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: java-p6spy   File: HibernateTest.java   Source Code and License Vote up 6 votes
@Test
public void jpaWithActiveSpanOnlyWithParent() {
  try (Scope activeSpan = mockTracer.buildSpan("parent").startActive(true)) {
    EntityManagerFactory entityManagerFactory =
        Persistence.createEntityManagerFactory("jpa_active_span_only");

    Employee employee = new Employee();
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    entityManager.persist(employee);
    entityManager.getTransaction().commit();
    entityManager.close();
    entityManagerFactory.close();

    assertNotNull(employee.id);
  }

  List<MockSpan> finishedSpans = mockTracer.finishedSpans();
  assertEquals(9, finishedSpans.size());
  checkSameTrace(finishedSpans);
  assertNull(mockTracer.scopeManager().active());
}
 
Example 2
Project: java-jdbc   File: HibernateTest.java   Source Code and License Vote up 6 votes
@Test
public void jpa_with_parent_and_active_span_only() {

  try (Scope ignored = mockTracer.buildSpan("parent").startActive(true)) {
    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();
  }

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(11, spans.size());
  checkSameTrace(spans);
  assertNull(mockTracer.activeSpan());
}
 
Example 3
Project: BecomeJavaHero   File: App4.java   Source Code and License Vote up 6 votes
public static void main(String[] args) {
	EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("pl.edu.bogdan.training.db.entity");
	EntityManager em = entityManagerFactory.createEntityManager();
	
	// begining of transaction
	em.getTransaction().begin();
	
	// Creating query in the way very similar to SQL
	Query query = em.createQuery("Select r from Role r where r.name = :name");
	query.setParameter("name", "ordinary");
	
	// We obtaining result as a list of entities
	List<Role> roles = query.getResultList();
	
	for (Role role : roles) {
		System.out.println(role.getName());
		for (User u : role.getUsers()) {
			System.out.println("     " + u.getLastName());
		}
	}
	
	em.getTransaction().commit();
	em.close();
	entityManagerFactory.close();
}
 
Example 4
Project: java-jdbc   File: HibernateTest.java   Source Code and License Vote up 6 votes
@Test
public void jpa_with_active_span_only() {
  EntityManagerFactory entityManagerFactory = Persistence
      .createEntityManagerFactory("jpa_active_span_only");

  Employee employee = new Employee();
  EntityManager entityManager = entityManagerFactory.createEntityManager();
  entityManager.getTransaction().begin();
  entityManager.persist(employee);
  entityManager.getTransaction().commit();
  entityManager.close();
  entityManagerFactory.close();

  assertNotNull(employee.id);

  List<MockSpan> finishedSpans = mockTracer.finishedSpans();
  assertEquals(0, finishedSpans.size());

  assertNull(mockTracer.activeSpan());
}
 
Example 5
Project: ProjetoFinalInitium   File: CidadeTest.java   Source Code and License Vote up 5 votes
@Test
public void deleteTest() {
	EntityManagerFactory factory = Persistence.createEntityManagerFactory("db1start");
	EntityManager manager = factory.createEntityManager();

	Cidade cidade = manager.find(Cidade.class, 3L);
	manager.getTransaction().begin();
	manager.remove(cidade);
	manager.getTransaction().commit();

	factory.close();

}
 
Example 6
Project: aries-jpa   File: PersistenceProviderTracker.java   Source Code and License Vote up 5 votes
/**
 * Create and close a dummy EMF to give the PersistenceProvider a chance to call
 * punit.addTransformer(). This has to occur as early as possible as weaving needs
 * to be done before the first entity class is loaded. So we can not wait till the
 * real DataSource is found.
 */
private void createAndCloseDummyEMF(PersistenceProvider provider) {
    DataSource dummyDataSource = new DummyDataSource();
    punit.setJtaDataSource(dummyDataSource);
    punit.setNonJtaDataSource(dummyDataSource);
    try {
        EntityManagerFactory emf = provider.createContainerEntityManagerFactory(punit, null);
        emf.close();
    } catch (Exception e) {
        LOGGER.debug("Error while creating the Dummy EntityManagerFactory to allow weaving.", e);
    }
    punit.setJtaDataSource(null);
    punit.setNonJtaDataSource(null);
}
 
Example 7
Project: osc-core   File: DBConnectionManager.java   Source Code and License Vote up 5 votes
public  void replaceDefaultDBPassword() throws Exception {
    try (Connection connection = getSQLConnection();
            PreparedStatement changePasswordStatement = connection.prepareStatement("ALTER USER " + this.connectionParams.getLogin().toUpperCase() + " SET PASSWORD ?")) {

        connection.setAutoCommit(false);

        String newPassword = RandomStringUtils.randomAscii(32);

        try {
            // change password in DB
            changePasswordStatement.setString(1, newPassword);
            changePasswordStatement.execute();

            // put password in keystore
            this.connectionParams.updatePassword(newPassword);

            connection.commit();
        } catch (Exception ex) {
            log.error("Error while changing DB password.", ex);

            try {
                connection.rollback();
            } catch (Exception he) {
                log.error("Error rolling back transaction", he);
            }

            throw ex;
        }
        EntityManagerFactory oldEmf = this.emf;
        // reinitialize session factory
        start(this.properties);

        try {
            oldEmf.close();
        } catch (PersistenceException pe) {
            // Ignore this
        }
    }
}
 
Example 8
Project: ProjetoFinalInitium   File: CidadeTest.java   Source Code and License Vote up 5 votes
@Test
public void selectSqlNativoTest() {
	EntityManagerFactory factory = Persistence.createEntityManagerFactory("db1start");
	EntityManager manager = factory.createEntityManager();

	Query query = manager.createNativeQuery("Select * from cidade c");
	List<Cidade> cidades = query.getResultList();

	factory.close();

}
 
Example 9
Project: BecomeJavaHero   File: App5.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
	EntityManagerFactory entityManagerFactory = Persistence
			.createEntityManagerFactory("pl.edu.bogdan.training.db.entity");
	EntityManager em = entityManagerFactory.createEntityManager();

	// begining of transaction
	em.getTransaction().begin();

	// Object used to create more sophisticated conditions
	CriteriaBuilder cb = em.getCriteriaBuilder();
	
	// this object is used to create query object
	CriteriaQuery<Role> cq = cb.createQuery(Role.class);
	
	// We set the root of query (we will use this root to getting values of columns)
	Root<Role> from = cq.from(Role.class);
	
	// we composing query using cb object
	cq.where(cb.equal(from.get("name"), "ordinary"));
	
	// creating query and executing it
	TypedQuery<Role> tq = em.createQuery(cq);
	List<Role> roles = tq.getResultList();
	
	
	for (Role role : roles) {
		System.out.println(role.getName());
	}

	em.getTransaction().commit();
	em.close();
	entityManagerFactory.close();
}
 
Example 10
Project: BecomeJavaHero   File: App2.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
	EntityManagerFactory entityManagerFactory 
	= Persistence.createEntityManagerFactory("pl.edu.bogdan.training.db.entity");
	EntityManager em = entityManagerFactory.createEntityManager();
	
	em.getTransaction().begin();
	
	User user = new User("Paweł", "Bogdan", 28, null);
	em.persist(user);
	em.getTransaction().commit();
	em.close();
	entityManagerFactory.close();
}
 
Example 11
Project: ProjetoFinalInitium   File: CidadeTest.java   Source Code and License Vote up 5 votes
@Test
public void metodoTest() {
	EntityManagerFactory factory = Persistence.createEntityManagerFactory("db1start");
	EntityManager manager = factory.createEntityManager();

	Cidade cidade = new Cidade();
	cidade.setNome("Maringa");
	
	manager.getTransaction().begin();
	manager.persist(cidade);
	manager.getTransaction().commit();

	factory.close();

}
 
Example 12
Project: minijax   File: LiquibaseHelper.java   Source Code and License Vote up 5 votes
static void closeQuietly(final EntityManagerFactory emf) {
    if (emf != null) {
        try {
            emf.close();
        } catch (final Exception ex) {
            LOG.warn("Error closing entity manager factory: {}", ex.getMessage(), ex);
        }
    }
}
 
Example 13
Project: minijax   File: CloseUtils.java   Source Code and License Vote up 5 votes
private static void closeEntityManagerFactory(final EntityManagerFactory emf) {
    try {
        if (emf != null && emf.isOpen()) {
            emf.close();
        }
    } catch (final Exception ex) {
        LOG.warn(ex.getMessage(), ex);
    }
}
 
Example 14
Project: java-course   File: Initialization.java   Source Code and License Vote up 5 votes
/**
 * {@inheritDoc}
 */
@Override
public void contextDestroyed(ServletContextEvent sce) {
    JPAEMFProvider.setEmf(null);
    EntityManagerFactory emf = (EntityManagerFactory) sce
            .getServletContext().getAttribute("my.application.emf");
    if (emf != null) {
        emf.close();
    }
}
 
Example 15
Project: appng-examples   File: SchemaExport.java   Source Code and License Vote up 4 votes
public static void main(String[] args) {
	EntityManagerFactory emf = Persistence.createEntityManagerFactory("mysql-testdb");
	emf.close();
}
 
Example 16
Project: hibernate-ogm-redis   File: DogBreedRunner.java   Source Code and License Vote up 4 votes
public static void main(String[] args) {

		TransactionManager tm = com.arjuna.ats.jta.TransactionManager.transactionManager();

		//build the EntityManagerFactory as you would build in in Hibernate Core
		EntityManagerFactory emf = Persistence.createEntityManagerFactory( "ogm-jpa-tutorial" );

		//Persist entities the way you are used to in plain JPA
		try {
			tm.begin();
			logger.infof( "About to store dog and breed" );
			EntityManager em = emf.createEntityManager();
			Breed collie = new Breed();
			collie.setName( "Collie" );
			em.persist( collie );
			Dog dina = new Dog();
			dina.setName( "Dina" );
			dina.setBreed( collie );
			em.persist( dina );
			Long dinaId = dina.getId();
			em.flush();
			em.close();
			tm.commit();

			//Retrieve your entities the way you are used to in plain JPA
			logger.infof( "About to retrieve dog and breed" );
			tm.begin();
			em = emf.createEntityManager();
			dina = em.find( Dog.class, dinaId );
			logger.infof( "Found dog %s of breed %s", dina.getName(), dina.getBreed().getName() );
			em.flush();
			em.close();
			tm.commit();

			emf.close();
		}
		catch ( Exception e ) {
			e.printStackTrace();
		}

	}
 
Example 17
Project: aries-jpa   File: AriesEntityManagerFactoryBuilder.java   Source Code and License Vote up 4 votes
private EntityManagerFactory createAndPublishEMF(Map<String, Object> overrides) {
	
	boolean makeTracker;
	String dbDriver;
	synchronized (this) {
		makeTracker = driver != null && tracker == null;
		dbDriver = driver; 
	}
	
	if(makeTracker) {
		ServiceTracker<?, ?> dsfTracker = new DSFTracker(containerContext, 
				this, dbDriver);
		synchronized (this) {
			tracker = dsfTracker;
			activeProps = overrides;
		}
		dsfTracker.open();
		
		synchronized (this) {
			if(emf == null) {
				throw new IllegalStateException("No database driver is currently available for class " + dbDriver);
			} else {
				return emf;
			}
		}
	} else {
		synchronized (this) {
			if(!complete) {
				throw new IllegalArgumentException("The persistence unit " + getPUName() + 
						" has incomplete configuration and cannot be created. The configuration is" + overrides);
			}
		}
	}
	
	final EntityManagerFactory tmp = provider.createContainerEntityManagerFactory(persistenceUnit, overrides);
	boolean register = false;
	synchronized (this) {
		if(emf == null) {
			emf = tmp;
			activeProps = overrides;
			register = true;
		}
	}
	if(register) {
		Dictionary<String, Object> props = createBuilderProperties(overrides);
		BundleContext uctx = bundle.getBundleContext();
		ServiceRegistration<EntityManagerFactory> tmpReg = 
				uctx.registerService(EntityManagerFactory.class, 
						(EntityManagerFactory) Proxy.newProxyInstance(getClass().getClassLoader(), 
								new Class<?>[] {EntityManagerFactory.class}, 
								new InvocationHandler() {
									
									@Override
									public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
										if("close".equals(method.getName())) {
											// Ignore close as per the spec
											return null;
										}
										return method.invoke(tmp, args);
									}
								}), props);
		
		synchronized (this) {
			if(emf == tmp) {
				reg = tmpReg;
			} else {
				register = false;
			}
		}
		
		if(!register) {
			tmpReg.unregister();
		}
	} else {
		tmp.close();
		synchronized (this) {
			return emf;
		}
	}
	return tmp;
}
 
Example 18
Project: testing_security_development_enterprise_systems   File: IdCreationTest.java   Source Code and License Vote up 4 votes
@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());
}
 
Example 19
Project: unibave-backend   File: Main.java   Source Code and License Vote up 4 votes
public static void main(String[] args) {
    EntityManagerFactory emf = Persistence
            .createEntityManagerFactory("unibave-jpa");
    //org.hibernate.jpa.HibernatePersistenceProvider
    
    //adiciona
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    Aluno ramon = new Aluno();
    ramon.setNome("Ramon");
    ramon.setCidade("Cidade Azul");

    AlunoContato contato = new AlunoContato();
    contato.setTelefone("48999999999");
    //em.persist(contato);
    ramon.addContato(contato);
    
    em.persist(ramon);
    tx.commit();
    em.close();
    //lista
    em = emf.createEntityManager();
    List<Aluno> alunos = em.createNamedQuery("aluno.lista", Aluno.class)
            .setMaxResults(10)
            .getResultList();
    alunos.forEach(a -> {
        System.out.println(a);
        a.getContatos().forEach(System.out::println);
    });
    em.close();
    //lista por cidade
    em = emf.createEntityManager();
    alunos = em.createNamedQuery("aluno.listaPorCidade", Aluno.class)
            .setParameter("cidade", "Cidade Azul")
            .setMaxResults(10)
            .getResultList();
    alunos.forEach(System.out::println);
    em.close();
    //atualiza
    em = emf.createEntityManager();
    tx = em.getTransaction();
    tx.begin();
    ramon = em.find(Aluno.class, ramon.getCodigo());
    ramon.setCidade("Tubarão");
    em.merge(ramon);
    tx.commit();
    //deleta
    tx = em.getTransaction();
    tx.begin();
    em.remove(ramon);
    tx.commit();
    em.close();      
    
    emf.close();
}
 
Example 20
Project: aries-jpa   File: PropsConfigurationTest.java   Source Code and License Vote up 3 votes
@Test
public void testReturnedEmfClose() throws InvalidSyntaxException, ConfigurationException {
	
	when(provider.createContainerEntityManagerFactory(eq(punit), 
			eq(singletonMap(PersistenceUnitTransactionType.class.getName(), JTA))))
		.thenReturn(emf);
	
	Map<String, Object> props = new Hashtable<String, Object>();
	props.put("javax.persistence.dataSource", ds);
	
	AriesEntityManagerFactoryBuilder emfb = new AriesEntityManagerFactoryBuilder(
			containerContext, provider, providerBundle, punit);
	
	EntityManagerFactory returnedEMF = emfb.createEntityManagerFactory(props);
	
	
	verify(punit).setNonJtaDataSource(ds);
	verify(punitContext).registerService(eq(EntityManagerFactory.class),
			any(EntityManagerFactory.class), argThat(servicePropsMatcher(JPA_UNIT_NAME, "test-props")));
	
	returnedEMF.close();
	
	verify(emfReg).unregister();
	verify(emf).close();
	
	emfb.close();
}