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:facades.PersonFacadeDB.java

@Override
public String getPerson(Integer id) throws NotFoundException {
    String result = "";
    //get person with this id from DB
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();/*from   w w  w  .  j  av a2 s.com*/
    try {
        Person p = em.find(Person.class, id);

        result = om.writeValueAsString(p);
        //            Query query = em.createNamedQuery("Person.findById").setParameter("id", id);
        //            List<Person> people = query.getResultList();

        //result = gson.toJson(people.get(0));
        //result = om.writeValueAsString(people.get(0));
    } catch (Exception e) {
        throw new NotFoundException("No person exists for the given id");
    } finally {
        em.close();
    }
    return result;
}

From source file:facades.PersonFacadeDB.java

@Override
public String getPersons() {

    String result = "";
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();/*  ww  w .  j a v  a2 s. c om*/

    try {
        Query query = em.createNamedQuery("Person.findAll");
        List<Person> people = query.getResultList();

        try {
            result = om.writeValueAsString(people);
        } catch (JsonProcessingException ex) {
            Logger.getLogger(PersonFacadeDB.class.getName()).log(Level.SEVERE, null, ex);
        }

    } finally {
        em.close();
    }
    return result;
}

From source file:ro.allevo.fintpws.model.UserEntity.java

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {

    EntityManagerFactory configEntityManagerFactory = Persistence.createEntityManagerFactory("fintpCFG");
    EntityManager emc = configEntityManagerFactory.createEntityManager();

    TypedQuery<RoleEntity> query = emc.createNamedQuery("RoleEntity.findUserAuthorities", RoleEntity.class);
    List<RoleEntity> authorities = query.setParameter("userid", userid).getResultList();
    return authorities;
}

From source file:net.sf.ehcache.openjpa.datacache.TestEhCache.java

@Test
public void testPersist() {
    EntityManagerFactory emf = em.getEntityManagerFactory();

    EntityManager em = emf.createEntityManager();
    PObject pc = new PObject("XYZ");
    em.getTransaction().begin();// w w w  .j a va 2s  .  co  m
    em.persist(pc);
    em.getTransaction().commit();
    Object oid = pc.getId();

    em.clear();
    // After clean the instance must not be in L1 cache
    assertFalse(em.contains(pc));
    // But it must be found in L2 cache by its OpenJPA identifier
    assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid)));

    PObject pc2 = em.find(PObject.class, oid);
    // After find(), the original instance is not in the L1 cache
    assertFalse(em.contains(pc));
    // After find(), the found instance is in the L1 cache
    assertTrue(em.contains(pc2));
    // The L2 cache must still hold the key   
    assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid)));
}

From source file:test.unit.be.fedict.eid.applet.beta.PersistenceTest.java

@Before
public void setUp() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    Ejb3Configuration configuration = new Ejb3Configuration();
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
    configuration.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
    configuration.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:beta");
    configuration.setProperty("hibernate.hbm2ddl.auto", "create");
    configuration.addAnnotatedClass(SessionContextEntity.class);
    configuration.addAnnotatedClass(FeedbackEntity.class);
    configuration.addAnnotatedClass(TestResultEntity.class);
    configuration.addAnnotatedClass(TestReportEntity.class);
    configuration.addAnnotatedClass(AdministratorEntity.class);
    EntityManagerFactory entityManagerFactory = configuration.buildEntityManagerFactory();

    this.entityManager = entityManagerFactory.createEntityManager();
    this.entityManager.getTransaction().begin();
}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * Installs the DB scheme used by Jubula.
 * /*w  ww . jav  a2  s  . co m*/
 * @param entityManagerFactory
 *            The factory to use to create the entity manager in which the
 *            installation will occur.
 * 
 * @return <code>true</code> if the installation was successful. Otherwise,
 *         <code>false</code>.
 * @throws PMDatabaseConfException
 *             if the scheme couldn't be installed
 * @throws JBException
 *             in case of configuration problems
 */
private static boolean installDbScheme(EntityManagerFactory entityManagerFactory)
        throws PMDatabaseConfException, JBException {

    EntityManager em = null;
    try {
        em = entityManagerFactory.createEntityManager();
        SchemaManager schemaManager = new SchemaManager(em.unwrap(ServerSession.class));
        schemaManager.replaceDefaultTables();

        createOrUpdateDBVersion(em);
        createOrUpdateDBGuard(em);
        return true;
    } catch (PersistenceException e) {
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause instanceof SQLException) {
            if (("08001").equals(((SQLException) rootCause).getSQLState())) { //$NON-NLS-1$
                log.error(Messages.TheDBAllreadyUseAnotherProcess, e);
                throw new JBException(rootCause.getMessage(), MessageIDs.E_DB_IN_USE);
            }
            log.error(Messages.NoOrWrongUsernameOrPassword, e);
            throw new JBException(e.getMessage(), MessageIDs.E_NO_DB_CONNECTION);
        }
        final String msg = Messages.ProblemInstallingDBScheme + StringConstants.DOT;
        log.error(msg);
        throw new PMDatabaseConfException(msg, MessageIDs.E_NO_DB_SCHEME);
    } finally {
        if (em != null) {
            try {
                em.close();
            } catch (Throwable e) {
                // ignore
            }
        }
    }
}

From source file:proyectodavid.Negocio.Pregunta.SA.SAPreguntaImp.java

public SAPreguntaImp() {

    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ProyectoDavidPU");

    this.entityManager = entityManagerFactory.createEntityManager();

}

From source file:edu.harvard.i2b2.fhirserver.ejb.AccessTokenBean.java

@PostConstruct
public void init() {
    try {//  www . jav  a  2  s .  c  o m
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("testPer");
        em = factory.createEntityManager();
        Random r = new Random();
        // createAccessToken("clientId232" + r.nextInt());
        // deleteAllAccessTokens();
        if (Config.openAccessToken != null) {
            createIfNotExistsDemoAccessToken();
        }
    } catch (Exception ex) {

        logger.error("", ex);
    }
}

From source file:facades.PersonFacadeDB.java

@Override
public RoleSchool addRole(String json, Integer id) throws NotFoundException {
    Person p = gson.fromJson(getPerson(id), Person.class);
    HashMap<String, String> map = new Gson().fromJson(json, new TypeToken<HashMap<String, String>>() {
    }.getType());//from  www . ja  va 2 s.co m

    String roleName = map.get("roleName");
    RoleSchool role;

    switch (roleName) {
    case "Teacher Assistant":
        //Create role
        RoleSchool ta = new TeacherAssistant();
        ta.setPerson(p);
        role = ta;
        break;
    case "Teacher":

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        String dateInString = map.get("date");
        Date date = new Date();

        try {
            date = formatter.parse(dateInString);
        } catch (ParseException e) {
            e.printStackTrace(System.out);
        }

        RoleSchool t = new Teacher(date, map.get("degree"));
        t.setPerson(p);
        role = t;
        break;
    case "Student":
        RoleSchool s = new Student(map.get("semester"));
        s.setPerson(p);
        role = s;
        break;
    default:
        throw new IllegalArgumentException("no such role");
    }
    //save this info
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    try {
        em.persist(role);
        transaction.commit();
        em.getEntityManagerFactory().getCache().evictAll();
    } catch (Exception e) {
        throw new NotFoundException("Couldnt add role");
    } finally {
        em.close();
    }

    return role;

}

From source file:com.ge.apm.service.data.DataService.java

public Object postDirectData(String tablename, List<Map> list) {
    if (tablename == null)
        return "{\"code\":\"1\",\"msg\":\"please input table_name\"}";
    if (list == null || list.isEmpty())
        return "{\"code\":\"1\",\"msg\":\"no data post\"}";
    String tableName = tablename.toLowerCase();
    String talbeClassName = "com.ge.apm.domain." + tabelNameToClassName(tableName);
    Class<?> table = getDao(talbeClassName);
    Map<String, String> fields = getFields(table);

    EntityManagerFactory emf = WebUtil.getBean(EntityManagerFactory.class);
    EntityManager em = emf.createEntityManager();
    int fortimes = list.size() / 50 + 1;//
    for (int j = 0; j < fortimes; j++) {
        List<Map> subList = list.subList(j * 50, (j + 1) * 50 < list.size() ? (j + 1) * 50 : list.size());

        em.getTransaction().begin();/*from  ww  w .  j  av  a 2 s . co  m*/
        Query query = null;
        for (int i = 0; i < subList.size(); i++) {
            Map<String, Object> map = subList.get(i);
            String outColumnStr = "insert into " + tableName + " (";
            String outValueStr = ") values(";
            String[] strs = insertColumn(fields, map);
            outColumnStr += strs[0];
            outValueStr += strs[1];
            String sql = outColumnStr + outValueStr + ")";
            query = em.createNativeQuery(sql);
            query.executeUpdate();
        }
        try {
            em.getTransaction().commit();
        } catch (Exception ex) {
            em.getTransaction().rollback();
            Logger.getLogger(DataGetAndPushController.class.getName()).log(Level.SEVERE, null, ex);
            em.close();
            return "{\"code\":\"1\",\"msg\":\"save failed\"}";//
        }
    }
    if (em != null) {
        em.close();
    }
    return "{\"code\":\"0\",\"msg\":\"save success\"}";//?
}