Example usage for javax.persistence EntityManagerFactory close

List of usage examples for javax.persistence EntityManagerFactory close

Introduction

In this page you can find the example usage for javax.persistence EntityManagerFactory close.

Prototype

public void close();

Source Link

Document

Close the factory, releasing any resources that it holds.

Usage

From source file:com.openmeap.model.ModelTestUtils.java

static public void resetTestDb() {
    if (persistenceBeans != null) {
        EntityManagerFactory emf = getEntityManagerFactory();
        emf.close();
        persistenceBeans.close();//  w w  w.  j  a  v  a2s .  c o m
    }
    persistenceBeans = null;
    File testDbFile = new File(OPENMEAP_TEST_DB);
    if (testDbFile.exists() && !testDbFile.delete()) {
        throw new RuntimeException("Could not delete " + OPENMEAP_TEST_DB);
    }
}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a busca de todos os usurios existentes no banco de dados.
 * @author Richel Sensineli/*from   w  w  w  . j  a v a 2s . co m*/
 * @param nome String - Nome do usurio
 * @return Collection list
 */
@Override
public Collection buscaTodosUsuarios() {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU");
    EntityManager em = emf.createEntityManager();
    Query q = em.createQuery("select u from UsuarioImpl u");
    Collection result = null;
    result = q.getResultList();
    em.clear();
    em.close();
    emf.close();
    return result;
}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para realizar a busca de usurio pelo ID.
 * @author Richel Sensineli/* w w  w . j  av a  2s.c  o m*/
 * @param id int - ID do usurio
 * @return Usuario usuario - Objeto Usuario
 */
@Override
public Usuario buscaUsuarioPorId(final int id) throws UsuarioNaoEncontradoException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU");
    EntityManager em = emf.createEntityManager();
    Usuario u = em.find(UsuarioImpl.class, id);
    if (u == null) {
        throw new UsuarioNaoEncontradoException("usuario no encontrado");
    }
    em.clear();
    em.close();
    emf.close();
    return u;
}

From source file:com.xebialabs.deployit.maven.AbstractDeployitMojo.java

protected void startServer() {
    if (!SERVER_STARTED) {
        getLog().info("STARTING DEPLOYIT SERVER");
        DeployItConfiguration context = new DeployItConfiguration();

        context.setDatabaseType(SetupDatabaseType.HSQLDB);
        context.setDatabaseDriverClass(//from   w w  w .j av a  2 s.c  o m
                SetupDatabaseType.getDefaultDatabaseDriverClass(context.getDatabaseType()));
        context.setHibernateDialect(SetupDatabaseType.getHibernateDialect(context.getDatabaseType()));
        context.setDatabaseURL(
                "jdbc:hsqldb:file:" + new File(outputDirectory, "./deployit.hdb").getPath() + ";shutdown=true");
        context.setDatabaseUsername(SetupDatabaseType.getDefaultUsername(context.getDatabaseType()));
        context.setDatabasePassword("");
        File deployitRepoDir = new File(outputDirectory, "deployit.repo");
        deployitRepoDir.mkdir();
        context.setApplicationRepositoryPath(deployitRepoDir.getPath());
        context.setHttpPort(getPort());
        context.setApplicationToDeployPath("importablePackages");
        context.setMinThreads(10);
        context.setMaxThreads(50);
        context.setSecured(false);
        context.setHttpServerName("localhost");

        context.save();

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("ad-repository",
                context.getCreationalJPAProperties());
        emf.close();

        final Server s = new Server(context, ReleaseInfo.getReleaseInfo());
        s.start();
        getLog().info("STARTED DEPLOYIT SERVER");
        SERVER_STARTED = true;
    }
}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a remoo de usurio.
 * @author Richel Sensineli//from w w w.  ja  va 2 s  .c o m
 * @param id int - ID do usurio
 * @throws UsuarioNaoEncontradoException - usurio no encontrado
 */
@Override
public void removeUsuario(final int id) throws UsuarioNaoEncontradoException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU");
    EntityManager em = emf.createEntityManager();

    Usuario u = em.find(UsuarioImpl.class, id);

    em.getTransaction().begin();
    if (u == null) {
        throw new UsuarioNaoEncontradoException("usuario no encontrado");
    } else {
        em.remove(u);
        em.getTransaction().commit();
    }
    em.clear();
    em.close();
    emf.close();

}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a criao de usurio
 * @author Richel Sensineli\//from  w  ww.ja va  2  s  .com
 * @param nome String - Nome do usurio
 * @param sobrenome String - Nome do usurio
 * @return Usuario usuario - Objeto Usurio
 */
@Override
public Usuario criaUsuario(final String nome, final String sobrenome) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU");
    EntityManager em = emf.createEntityManager();

    UsuarioImpl user = new UsuarioImpl();
    user.setNome(nome);
    user.setSobrenome(sobrenome);

    em.getTransaction().begin();
    try {
        em.persist(user);
        em.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
        em.getTransaction().rollback();
    }

    em.clear();
    em.close();
    emf.close();

    return user;
}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a atualizao do usurio
 * @author Richel Sensineli/*from  w ww  .  j a  v a2s.co m*/
 * @param id int - ID do usurio
 * @param nome String - Nome do usurio
 * @param sobrenome String - Nome do usurio
 */
@Override
public void updateUsuario(final int id, final String nome, final String sobrenome)
        throws UsuarioNaoEncontradoException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU");
    EntityManager em = emf.createEntityManager();

    UsuarioImpl user = em.find(UsuarioImpl.class, id);
    user.setNome(nome);
    user.setSobrenome(sobrenome);

    em.getTransaction().begin();
    try {
        em.merge(user);
        em.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
        em.getTransaction().rollback();
    }

    em.clear();
    em.close();
    emf.close();
}

From source file:com.nokia.helium.metadata.tests.TestORMFMPPLoader.java

/**
 * Populates the LogFile table with basic data.
 * @throws MetadataException//from   w  ww.  ja  va2 s .  co m
 * @throws IOException
 */
@Before
public void populateDatabase() throws MetadataException, IOException {
    File tempdir = new File(System.getProperty("test.temp.dir"));
    tempdir.mkdirs();
    database = new File(tempdir, "test_db");
    if (database.exists()) {
        FileUtils.forceDelete(database);
    }
    EntityManagerFactory factory = FactoryManager.getFactoryManager().getEntityManagerFactory(database);
    EntityManager em = factory.createEntityManager();
    try {
        em.getTransaction().begin();
        for (int i = 0; i < 2000; i++) {
            LogFile lf = new LogFile();
            lf.setPath("log" + String.format("%04d", i));
            em.persist(lf);
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().commit();
        }
        em.close();
        factory.close();
    }
}

From source file:BO.UserHandler.java

private User getUserByEmail(String email) {
    User tempUser;/*w ww  .  ja  v a2s . c  o m*/

    EntityManager em;
    EntityManagerFactory emf;

    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        tempUser = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email")
                .setParameter("email", email).getSingleResult();
        return tempUser;
    } catch (NoResultException e) {
        throw (e);
    } catch (Exception e) {
        throw (e);
    } finally {
        if (em != null) {
            em.close();
        }
        if (emf != null) {
            emf.close();
        }
    }
}

From source file:com.boylesoftware.web.AbstractWebApplication.java

/**
 * Clean-up the application object./*w  w w.  j  a v a2s. com*/
 */
private void cleanup() {

    // get the log
    final Log log = LogFactory.getLog(AbstractWebApplication.class);
    log.debug("destroying the web-application");

    // shutdown the executors
    if (this.executors != null) {
        log.debug("shutting down the request processing executors...");
        this.executors.shutdown();
        try {
            boolean success = true;
            if (!this.executors.awaitTermination(30, TimeUnit.SECONDS)) {
                log.warn("could not shutdown the request processing"
                        + " executors in 30 seconds, trying to force" + " shutdown...");
                this.executors.shutdownNow();
                if (!this.executors.awaitTermination(30, TimeUnit.SECONDS)) {
                    log.error("could not shutdown the request processing" + " executors");
                    success = false;
                }
            }
            if (success)
                log.debug("request processing executors shut down");
        } catch (final InterruptedException e) {
            log.warn("waiting for the request processing executors to" + " shutdown was interrupted");
            this.executors.shutdownNow();
            Thread.currentThread().interrupt();
        } finally {
            this.executors = null;
        }
    }

    // destroy custom application
    log.debug("destroying custom application");
    try {
        this.destroy();
    } catch (final Exception e) {
        log.error("error destroying custom application", e);
    }

    // forget the router configuration
    this.routerConfiguration = null;

    // close and forget the entity manager factory
    final EntityManagerFactory emf = this.services.getEntityManagerFactory();
    if (emf != null) {
        this.services.setEntityManagerFactory(null);
        try {
            log.debug("closing persistence manager factory");
            emf.close();
        } catch (final Exception e) {
            log.error("error shutting down the application", e);
        }
    }

    // forget user locale finder
    this.services.setUserLocaleFinder(null);

    // close and forget the validator factory
    final ValidatorFactory vf = this.services.getValidatorFactory();
    if (vf != null) {
        this.services.setValidatorFactory(null);
        try {
            log.debug("closing validator factory");
            vf.close();
        } catch (final Exception e) {
            log.error("error shutting down the application", e);
        }
    }

    // forget the authentication service
    this.services.setAuthenticationService(null);
}