Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

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

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:com.headissue.pigeon.admin.AdminSurveyHandler.java

public int createSurvey(SurveyParameter p) {
    checkNotNull(p, "parameter is null");
    checkNotNull(p.getSurvey(), "survey values are null");
    Survey _survey = adminSurveyService.createSurvey(p.getSurvey(), new Date(p.getTimestamp()));
    EntityManager _manager = factory.createEntityManager();
    try {/*from  w w w .  j  a v a  2s . c  o m*/
        _manager.getTransaction().begin();
        _manager.persist(_survey);
        _manager.getTransaction().commit();
        return _survey.getId();
    } catch (Exception e) {
        LogUtils.warn(log, e, "save the survey failed");
        if (_manager.getTransaction().isActive()) {
            _manager.getTransaction().rollback();
        }
        return 0;
    } finally {
        _manager.close();
    }
}

From source file:com.headissue.pigeon.admin.AdminSurveyHandler.java

public int overwriteSurvey(SurveyParameter p) {
    checkNotNull(p, "parameter is null");
    checkNotNull(p.getSurvey(), "survey values are null");
    EntityManager _manager = factory.createEntityManager();
    try {//from  www. j a v  a 2  s.  c om
        _manager.getTransaction().begin();
        Survey _survey = _manager.find(Survey.class, p.getSurveyId());
        adminSurveyService.mergeSurvey(_survey, p.getSurvey(), new Date(p.getTimestamp()), _manager);
        _manager.getTransaction().commit();
        return _survey.getId();
    } catch (Exception e) {
        LogUtils.warn(log, e, "save the survey failed");
        if (_manager.getTransaction().isActive()) {
            _manager.getTransaction().rollback();
        }
        return 0;
    } finally {
        _manager.close();
    }
}

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

@Override
public List<CheckDocument> findAllForEmployer(Employer employer) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<CheckDocument> list = new LinkedList<>();
    try {// w  w  w .  ja v  a 2 s .co  m
        em.getTransaction().begin();

        TypedQuery<CheckDocument> query = em.createNamedQuery("CheckDocument.findAllForEmployer",
                CheckDocument.class);
        query.setParameter("employer", employer);
        list = query.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(BasicSkillRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list;
}

From source file:com.emc.plants.service.impl.LoginBean.java

/**
 * Update an existing user./*ww  w .  j av a 2s  .co  m*/
 *
 * @param customerID The customer ID.
 * @param firstName First name.
 * @param lastName Last name.
 * @param addr1 Address line 1.
 * @param addr2 Address line 2.
 * @param addrCity City address information.
 * @param addrState State address information.
 * @param addrZip Zip code address information.
 * @param phone User's phone number.
 * @return CustomerInfo
 */
public CustomerInfo updateUser(String customerID, String firstName, String lastName, String addr1, String addr2,
        String addrCity, String addrState, String addrZip, String phone) {
    CustomerInfo customerInfo = null;
    // TODO: lowp: no lock check is performed to see if cust data has changed since fetch!
    /*
     customerHome = (CustomerHome) Util.getEJBLocalHome("java:comp/env/ejb/Customer",
     com.ibm.websphere.samples.pbwjpa.CustomerHome.class);
             
     Customer customer = customerHome.findByPrimaryKeyUpdate(customerID);
     customer.update(firstName, lastName, addr1, addr2, addrCity, addrState, addrZip, phone);
     customerInfo = new CustomerInfo(customer);
     */
    EntityManager em = entityManagerFactory.createEntityManager();
    em.getTransaction().begin();
    Customer c = em.find(Customer.class, customerID);
    em.lock(c, LockModeType.WRITE);
    em.refresh(c);
    // TODO: lowp: test and set for update performance?
    c.setFirstName(firstName);
    c.setLastName(lastName);
    c.setAddr1(addr1);
    c.setAddr2(addr2);
    c.setAddrCity(addrCity);
    c.setAddrState(addrState);
    c.setAddrZip(addrZip);
    c.setPhone(phone);

    customerInfo = new CustomerInfo(c);
    em.getTransaction().commit();
    return customerInfo;
}

From source file:com.headissue.pigeon.service.AdminSurveyServiceTest.java

EntityManager mergeSurvey(SurveyValue _value) throws Exception {
    EntityManager _manager = factory.createEntityManager();
    try {//  www  .j  a  va 2s .c  om
        _manager.getTransaction().begin();
        Survey s = _manager.find(Survey.class, survey.getId());
        adminSurveyService.mergeSurvey(s, _value, UPDATE_DATE, _manager);
        _manager.persist(s);
        _manager.getTransaction().commit();
        survey = s;
    } catch (Exception e) {
        if (_manager.getTransaction().isActive()) {
            _manager.getTransaction().rollback();
        }
        throw e;
    }
    return _manager;
}

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

/**
 * Flush changes to the datastore, commit transaction, release em.
 * @throws SocialSiteException on any error
 *///  w ww.j ava 2 s .c  om
public void flush() throws SocialSiteException {
    try {
        EntityManager em = getEntityManager(true);
        em.getTransaction().commit();
    } catch (PersistenceException pe) {
        throw new SocialSiteException(pe);
    }
}

From source file:com.headissue.pigeon.survey.answer.AnswerHandler.java

public void receiveAnswer(Session _session, AnswerParameter p) {
    checkPreCondition(_session, p);//from  www  . j  a  va 2 s  .c o m
    EntityManager _manager = factory.createEntityManager();
    try {
        _manager.getTransaction().begin();
        Survey _survey = _manager.find(Survey.class, p.getSurveyId());
        checkNotNull(_survey, "unknown survey '%s'", p.getSurveyId());
        int _mapId = userMapService.getUserMapId(_session);
        final UserMap map;
        if (_mapId <= 0 || _mapId != p.getMapId()) {
            map = createUserMap(_survey, p, _manager);
        } else {
            map = loadUserMap(_survey, _mapId, _manager);
        }
        checkNotNull(map, "unknown user map for survey '%s'", p.getSurveyId());
        Date _timestamp = new Date(p.getTimestamp());
        for (UserAnswerValue _value : p.getValues().getAnswers()) {
            Question _question = findQuestion(_survey, _value.getQuestionId());
            if (_question == null) {
                continue;
            }
            storeAnswer(_survey, _question, map, _value, _manager, _timestamp);
        }
        _manager.getTransaction().commit();
        checkTrue(map.getId() != 0, "user map can not created for survey '%s'", p.getSurveyId());
        userMapService.setUserMapId(_session, map.getId());
    } catch (Exception e) {
        LogUtils.warn(log, "receiveAnswer: processing is failed");
        throw new AnswerException("processing is failed", e);
    } finally {
        _manager.close();
    }
}

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

private void addUpdateDeleteEntity(Object entity, Action action) {
    EntityManager em = getEntityManager();
    try {//w  ww  .  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:info.san.books.app.model.listener.LivreListener.java

@EventHandler
public void handle(LivreDeletedEvent e) {
    EntityManager em = Persistence.getInstance().createEntityManager();

    EntityTransaction t = em.getTransaction();

    t.begin();/*from   w w w.j  a  va 2  s  .c om*/

    LivreEntry entry = em.getReference(LivreEntry.class, e.getIsbn());
    em.remove(entry);

    t.commit();
}

From source file:com.headissue.pigeon.service.AdminSurveyServiceTest.java

@Before
public void setUp() throws Exception {
    injector.injectMembers(this);

    SurveyValue _value = getSurveyValue("testSurvey.json");
    survey = adminSurveyService.createSurvey(_value, CREATE_DATE);
    EntityManager _manager = factory.createEntityManager();
    _manager.getTransaction().begin();
    _manager.persist(survey);/*from w  w w  . j  a  va2s.c  o  m*/
    _manager.getTransaction().commit();
    _manager.close();

    UserAnswerValues a = new UserAnswerValues();
    a.setPageKey("testSurvey");
    a.setUserData("gans");
    a.setUserKey("gustav");
    a.setAnswers(new ArrayList<UserAnswerValue>());
    AnswerParameter p = new AnswerParameter();
    p.setSurveyId(survey.getId());
    p.setTimestamp(ANSWER_DATE.getTime());
    p.setValues(a);
    LogUtils.debug(log, "survey id:    %s", survey.getId());
    for (Question q : survey.getQuestions()) {
        LogUtils.debug(log, "querstion id: %s", q.getId());
        UserAnswerValue v = new UserAnswerValue();
        v.setQuestionId(q.getId());
        v.setValues(Arrays.asList(q.getAnswers().get(0).getText()));
        a.getAnswers().add(v);
        for (QuestionText qt : q.getAnswers()) {
            LogUtils.debug(log, "answert id:   %s", qt.getId());
        }
    }

    SessionManager _sessionManager = new SessionManager();
    AnswerHandler _answerHandler = injector.getInstance(AnswerHandler.class);
    _answerHandler.receiveAnswer(_sessionManager.getCurrentSession(), p);
}