Example usage for javax.persistence EntityManager persist

List of usage examples for javax.persistence EntityManager persist

Introduction

In this page you can find the example usage for javax.persistence EntityManager persist.

Prototype

public void persist(Object entity);

Source Link

Document

Make an instance managed and persistent.

Usage

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());/*w  ww.ja  v  a2  s.c  om*/

    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:org.drools.task.service.TaskServiceEscalationBaseTest.java

public void testUnescalatedDeadlinesOnStartup() throws Exception {
    Map vars = new HashedMap();
    vars.put("users", users);
    vars.put("groups", groups);

    //Reader reader;
    Reader reader = new InputStreamReader(
            TaskServiceEscalationBaseTest.class.getResourceAsStream("../QueryData_UnescalatedDeadlines.mvel"));
    List<Task> tasks = (List<Task>) eval(reader, vars);
    long now = ((Date) vars.get("now")).getTime();

    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();// w  w w.j a v a  2  s . c  om
    for (Task task : tasks) {
        // for this one we put the task in directly;
        em.persist(task);
    }
    em.getTransaction().commit();

    // now create a new service, to see if it initiates from the DB correctly
    MockEscalatedDeadlineHandler handler = new MockEscalatedDeadlineHandler();
    TaskService local = new TaskService(emf, SystemEventListenerFactory.getSystemEventListener(), handler);

    handler.wait(3, 30000);

    assertEquals(3, handler.list.size());

    Item item0 = handler.list.get(0);
    assertEquals(item0.getDeadline().getDate().getTime(), now + 20000);

    Item item1 = handler.list.get(1);
    assertEquals(item1.getDeadline().getDate().getTime(), now + 22000);

    Item item2 = handler.list.get(2);
    assertEquals(item2.getDeadline().getDate().getTime(), now + 24000);
}

From source file:com.sun.socialsite.business.impl.JPAPersistenceStrategy.java

/**
 * Store object using an existing transaction.
 * @param obj the object to persist/*w w w  . j  a v a2s  .  co  m*/
 * @return the object persisted
 * @throws SocialSiteException on any error
 */
public Object store(Object obj) throws SocialSiteException {
    EntityManager em = getEntityManager(true);
    if (!em.contains(obj)) {
        // If entity is not managed we can assume it is new
        em.persist(obj);
    }
    return obj;
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

public void save(T entity) throws ServiceException {
    try {/*  w w  w.  ja  v  a  2 s  .  c om*/
        EntityManager entityManager = currentEntityManager();
        entityManager.getTransaction().begin();

        entityManager.persist(entity);

        commitTransaction();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        rollbackTransaction();
        throw new ServiceException("Can't update object", e);
    } finally {
        closeEntityManager();
    }
}

From source file:com.yahoo.sql4d.indexeragent.meta.DBHandler.java

private void addUpdateDeleteEntity(Object entity, Action action) {
    EntityManager em = getEntityManager();
    try {//from  w w  w  .  j av  a 2s . c  om
        em.getTransaction().begin();
        switch (action) {
        case ADD:
            em.persist(entity);
            break;
        case UPDATE:
            em.merge(entity);
            break;
        case DELETE:
            em.remove(entity);
            break;
        }
    } catch (RuntimeException e) {
        log.error("Something wrong persisting/merging/removing entity {}, so rolling back . Exception is {}",
                entity, ExceptionUtils.getStackTrace(e));
        em.getTransaction().rollback();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().commit();
        }
        em.close();
    }
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java

@Override
public boolean create(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {/*from   w w w . j av  a 2s  .c o  m*/
        em.getTransaction().begin();
        em.persist(vacancy);
        em.getTransaction().commit();
        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(VacancyRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

From source file:org.spc.ofp.tubs.domain.common.CommonRepository.java

public boolean saveImportStatus(final ImportStatus status) {
    boolean success = false;
    final EntityManager mgr = emf.createEntityManager();
    final EntityTransaction xa = mgr.getTransaction();
    xa.begin();//  w  w w.  ja va  2  s  . c om
    try {
        if (status.getId() > 0L) {
            mgr.merge(status);
        } else {
            mgr.persist(status);
        }
        xa.commit();
        success = true;
    } catch (Exception ignoreMe) {
        rollbackQuietly(xa);
    } finally {
        mgr.close();
    }
    return success;
}

From source file:org.rhq.enterprise.server.drift.JPADriftServerBeanTest.java

public void copyChangeSet() {
    // first create the change set that will be copied
    final JPADriftChangeSet changeSet = new JPADriftChangeSet(null, 0, COVERAGE, null);
    changeSet.setDriftHandlingMode(normal);

    final JPADrift drift1 = new JPADrift(changeSet, "drift.1", FILE_ADDED, null, driftFile1);
    final JPADrift drift2 = new JPADrift(changeSet, "drift.2", FILE_ADDED, null, driftFile2);

    final JPADriftSet driftSet = new JPADriftSet();
    driftSet.addDrift(drift1);//from  www  .  jav a 2s.c  om
    driftSet.addDrift(drift2);

    // next create the drift definition
    final DriftDefinition driftDef = new DriftDefinition(new Configuration());
    driftDef.setName("test::copyChangeSet");
    driftDef.setEnabled(true);
    driftDef.setDriftHandlingMode(normal);
    driftDef.setInterval(2400L);
    driftDef.setBasedir(new DriftDefinition.BaseDirectory(fileSystem, "/foo/bar/test"));
    driftDef.setResource(resource);

    // persist the change set and drift definition
    executeInTransaction(new TransactionCallback() {
        @Override
        public void execute() throws Exception {
            EntityManager em = getEntityManager();
            em.persist(changeSet);
            em.persist(driftDef);
            em.persist(driftSet);
            changeSet.setInitialDriftSet(driftSet);
            em.merge(changeSet);
        }
    });

    jpaDriftServer.copyChangeSet(getOverlord(), changeSet.getId(), driftDef.getId(), resource.getId());

    // verify that the change set was created for the definition
    JPADriftChangeSetCriteria criteria = new JPADriftChangeSetCriteria();
    criteria.addFilterDriftDefinitionId(driftDef.getId());
    criteria.addFilterCategory(COVERAGE);

    PageList<JPADriftChangeSet> changeSets = jpaDriftServer.findDriftChangeSetsByCriteria(getOverlord(),
            criteria);

    assertEquals("Expected to get back one change set", 1, changeSets.size());

    JPADriftChangeSet newChangeSet = changeSets.get(0);
    Set<JPADrift> expectedDrifts = new HashSet<JPADrift>(asList(drift1, drift2));
    Set<JPADrift> actualDrifts = newChangeSet.getDrifts();

    AssertUtils.assertCollectionMatchesNoOrder("The change set drifts were not copied correctly",
            expectedDrifts, actualDrifts, "changeSet", "newDriftFile");
}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a criao de usurio
 * @author Richel Sensineli\/*w  w  w . j ava  2 s  .c om*/
 * @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:org.apache.openjpa.jdbc.meta.strats.AbstractLobTest.java

public void testLifeCycleInsertFlushModify() {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();/*w ww  .  j a v a 2s .  co m*/
    LobEntity le = newLobEntity(createLobData(), 1);
    em.persist(le);
    em.flush();
    changeStream(le, createLobData2());
    em.getTransaction().commit();
    em.close();
}