Example usage for javax.persistence EntityManagerFactory createEntityManager

List of usage examples for javax.persistence EntityManagerFactory createEntityManager

Introduction

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

Prototype

public EntityManager createEntityManager();

Source Link

Document

Create a new application-managed EntityManager.

Usage

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para realizar a busca de usurio pelo ID.
 * @author Richel Sensineli/*ww w .j a va 2  s . com*/
 * @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:edu.harvard.i2b2.fhirserver.ejb.AuthTokenBean.java

@PostConstruct
public void init() {
    try {/*from  w w w . j  av a  2  s .  co m*/
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("testPer");
        em = factory.createEntityManager();
        Random r = new Random();
        String rs = Integer.toString(r.nextInt());
        createAuthToken(rs, rs, rs, rs, rs, rs, rs, rs);
        logger.info("total:" + totalCount());
        // createAuthToken("clientId232" + r.nextInt());
    } catch (Exception ex) {
        logger.error("", ex);
    }
}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a remoo de usurio.
 * @author Richel Sensineli/*w  ww . j a  va 2s.  co 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:com.nokia.helium.metadata.tests.TestORMFMPPLoader.java

/**
 * Populates the LogFile table with basic data.
 * @throws MetadataException/*from w w  w . ja  va  2  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:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a atualizao do usurio
 * @author Richel Sensineli//w w w  .j  av a 2s.c  o 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:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a criao de usurio
 * @author Richel Sensineli\//from   www.j a va2s .co m
 * @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:com.edugility.substantia.substance.TestCasePerson.java

@Test
public void testingJPA() throws Exception {
    final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test");
    assertNotNull(emf);/*from   w w  w  .  ja  v  a  2 s  .  com*/

    final EntityManager em = emf.createEntityManager();
    assertNotNull(em);

    final EntityTransaction et = em.getTransaction();
    assertNotNull(et);
    et.begin();

    final Person p = new Person();
    em.persist(p);
    em.flush();
    assertFalse(p.isTransient());
    assertTrue(p.isVersioned());
    assertEquals(Long.valueOf(1L), p.getId());
    assertEquals(Integer.valueOf(1), p.getVersion());

    et.commit();
    et.begin();

    final Person p2 = em.find(Person.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
    assertNotNull(p2);
    assertFalse(p2.isTransient());
    assertTrue(p2.isVersioned());
    assertEquals(Long.valueOf(1L), p2.getId());
    assertEquals(Integer.valueOf(1), p2.getVersion());

    et.commit();
    et.begin();

    final Person p3 = em.getReference(Person.class, 1L);
    assertNotNull(p3);
    assertFalse(p3.isTransient());
    assertTrue(p3.isVersioned());
    assertEquals(Long.valueOf(1L), p3.getId());
    assertEquals(Integer.valueOf(2), p3.getVersion());

    et.commit();
    et.begin();

    assertTrue(em.contains(p));
    em.remove(p);

    et.commit();

    em.close();

    emf.close();
}

From source file:facades.PersonFacadeDB.java

@Override
public Person delete(Integer id) throws NotFoundException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();// w w  w  .j ava 2 s .  com

    Person p = em.find(Person.class, id);

    if (p == null) {
        transaction.rollback();
        throw new NotFoundException("No person for the given id");
    } else {
        em.remove(p);
        transaction.commit();
    }

    return p;
}

From source file:facades.PersonFacadeDB.java

@Override
public Person addPerson(String json) {
    //make person from Json
    Person p = gson.fromJson(json, Person.class);

    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();/*from w w w . ja v a 2 s .  com*/

    try {
        em.persist(p);
        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
    } finally {
        em.close();
    }
    return p;
}

From source file:net.officefloor.tutorial.transactionhttpserver.TransactionHttpServerTest.java

/**
 * Ensure the JPA connects to database./*from  w ww.  ja  v a  2 s  .c  o m*/
 */
public void testJpa() throws Exception {

    // Request page to allow time for database setup
    this.doRequest("http://localhost:7878/users.woof");

    // Obtain entity manager
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("example");
    EntityManager manager = factory.createEntityManager();

    // Ensure can obtain user and person
    Query query = manager.createQuery("SELECT U FROM User U");
    User user = (User) query.getSingleResult();
    assertEquals("Incorrect user name", "daniel", user.getUserName());
    Person person = user.getPerson();
    assertEquals("Incorrect person name", "Daniel Sagenschneider", person.getFullName());

    // Ensure persist user and person
    User newUser = new User();
    newUser.setUserName("test");
    Person newPerson = new Person();
    newPerson.setFullName("TEST");
    newPerson.setUser(newUser);
    manager.persist(newPerson);
    manager.close();

    // Ensure user and person persisted
    manager = factory.createEntityManager();
    User retrievedUser = manager.find(User.class, newUser.getId());
    assertEquals("Incorrect retrieved user name", "test", retrievedUser.getUserName());
    Person retrievedPerson = retrievedUser.getPerson();
    assertEquals("Incorrect retrieved full name", "TEST", retrievedPerson.getFullName());

    // Close persistence
    factory.close();
}