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.bitplan.vzjava.TestVZJPA.java

/**
 * test importing power VAlues in XML Format
 * /*www  . j ava  2 s  .  c o  m*/
 * @throws Exception
 */
// https://github.com/WolfgangFahl/com.bitplan.vzjava/issues/5
@Test
public void testImportXml() throws Exception {
    // open the testdatabase
    VZDB vzdb = new VZDB("demo");
    // get the power values from the XML file
    File powerValueXmlFile = new File("src/test/data/vzdb/powervalues.xml");
    String xml = FileUtils.readFileToString(powerValueXmlFile);
    PowerValueManagerDao pvm = (PowerValueManagerDao) PowerValueManagerDao.getFactoryStatic().fromXML(xml);
    List<PowerValue> powerValues = pvm.getElements();
    // there should be 74669 power values in this test set
    assertEquals("xml import should have new Color(0x of records", 74669, powerValues.size());
    // delete existing data from the test database
    EntityManager em = vzdb.getEntityManager();
    em.getTransaction().begin();
    Query dquery = em.createNativeQuery("delete from data");
    dquery.executeUpdate();
    em.getTransaction().commit();

    String from = "2017-01-31 20:00:00";
    String to = "2017-03-24 14:00:00";
    em.getTransaction().begin();
    for (PowerValue powerValue : powerValues) {
        em.persist(powerValue);
    }
    em.getTransaction().commit();
    int channel = 4;
    ChannelMode channelMode = ChannelMode.Power;
    pvm.setVzdb(vzdb);
    List<PowerValue> dbPowerValues = pvm.get(from, to, channel, channelMode);
    assertTrue(String.format("database should have more than 74400 of imported records but has %5d",
            dbPowerValues.size()), dbPowerValues.size() > 74400);
}

From source file:info.san.books.app.model.listener.LivreListener.java

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

    EntityTransaction t = em.getTransaction();

    t.begin();//from  w  ww  . j  a v  a2 s.c  o m

    LivreEntry livre = em.find(LivreEntry.class, e.getIsbn());
    AuteurEntry auteur = em.find(AuteurEntry.class, e.getAuteurId());

    livre.getAuteurs().add(auteur);
    auteur.getLivres().add(livre);

    t.commit();
}

From source file:info.san.books.app.model.listener.LivreListener.java

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

    EntityTransaction t = em.getTransaction();

    t.begin();//from   w w  w. j a  va2  s .com

    LivreEntry livre = em.find(LivreEntry.class, e.getIsbn());
    AuteurEntry auteur = em.find(AuteurEntry.class, e.getAuteurId());

    livre.getAuteurs().remove(auteur);
    auteur.getLivres().remove(livre);

    t.commit();
}

From source file:com.doculibre.constellio.wicket.panels.admin.featuredLink.AddEditFeaturedLinkPanel.java

@Override
protected void onSave(AjaxRequestTarget target) {
    FeaturedLink featuredLink = featuredLinkModel.getObject();

    AdminCollectionPanel collectionAdminPanel = (AdminCollectionPanel) findParent(AdminCollectionPanel.class);
    RecordCollection collection = collectionAdminPanel.getCollection();
    featuredLink.setRecordCollection(collection);

    FeaturedLinkServices featuredLinkServices = ConstellioSpringUtils.getFeaturedLinkServices();
    EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();
    if (!entityManager.getTransaction().isActive()) {
        entityManager.getTransaction().begin();
    }/*ww  w.ja v a 2 s. c  o m*/
    featuredLinkServices.makePersistent(featuredLink);
    entityManager.getTransaction().commit();
}

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

/**
 * Create a new user.//from  w  w w. ja  v a  2 s  .  co  m
 *
 * @param customerID The new customer ID.
 * @param password The password for 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
 */
//@Transactional
public CustomerInfo createNewUser(String customerID, String password, String firstName, String lastName,
        String addr1, String addr2, String addrCity, String addrState, String addrZip, String phone) {
    CustomerInfo customerInfo = null;

    /*
     customerHome = (CustomerHome) Util.getEJBLocalHome("java:comp/env/ejb/Customer",
     com.ibm.websphere.samples.pbwjpa.CustomerHome.class);
             
     try
     {
     // Only create new user if it doesn't already exist.
      customerHome.findByPrimaryKeyUpdate(customerID);
      }
      catch (ObjectNotFoundException onfe)
      {
      // Create customer and return true if all goes well.
       Customer customer = 
       customerHome.create(new CustomerKey(customerID), password, firstName, 
       lastName, addr1, addr2, addrCity, addrState,
       addrZip, phone);
               
       if (customer != null)
       customerInfo = new CustomerInfo(customer);
       }
       }
       catch (FinderException e) { e.printStackTrace(); }
       catch (CreateException e) { e.printStackTrace(); }
       */
    Customer c = new Customer(customerID, password, firstName, lastName, addr1, addr2, addrCity, addrState,
            addrZip, phone);
    EntityManager em = entityManagerFactory.createEntityManager();
    em.getTransaction().begin();
    em.persist(c);
    em.flush();
    em.getTransaction().commit();
    customerInfo = new CustomerInfo(c);
    return customerInfo;
}

From source file:nl.b3p.viewer.admin.stripes.CycloramaConfigurationActionBean.java

public Resolution save() throws KeyStoreException {
    try {//from w ww.j a v  a2  s  .c o m
        if (key != null) {
            String privateBase64Key = getBase64EncodedPrivateKeyFromPfxUpload(key.getInputStream(),
                    account.getPassword());
            account.setPrivateBase64Key(privateBase64Key);
            account.setFilename(key.getFileName());
            key.delete();
        } else {
            if (account.getPrivateBase64Key() == null) {
                context.getValidationErrors().add("Key", new SimpleError(
                        getBundle().getString("viewer_admin.cycloramaconfigurationactionbean.pfx")));
            }
        }
        EntityManager em = Stripersist.getEntityManager();
        em.persist(account);
        em.getTransaction().commit();

    } catch (Exception ex) {
        context.getValidationErrors().add("Key", new SimpleError(
                getBundle().getString("viewer_admin.cycloramaconfigurationactionbean.keywrong")));
        log.error("Something went wrong with reading the key", ex);
    }
    return view();
}

From source file:nl.b3p.kaartenbalie.struts.KaartenbalieCrudAction.java

/** Execute method which handles all incoming request.
 *
 * @param mapping action mapping//www .jav  a 2 s  . c  om
 * @param dynaForm dyna validator form
 * @param request servlet request
 * @param response servlet response
 *
 * @return ActionForward defined by Apache foundation
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) method.">
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Object identity = null;

    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);

        ActionForward forward = null;
        String msg = null;

        EntityManager em = getEntityManager();
        EntityTransaction tx = em.getTransaction();

        try {
            tx.begin();

            forward = super.execute(mapping, form, request, response);

            tx.commit();

            return forward;
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured, rollback", e);

            if (e instanceof org.hibernate.JDBCException) {
                msg = e.toString();
                SQLException sqle = ((org.hibernate.JDBCException) e).getSQLException();
                msg = msg + ": " + sqle;
                SQLException nextSqlE = sqle.getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else if (e instanceof java.sql.SQLException) {
                msg = e.toString();
                SQLException nextSqlE = ((java.sql.SQLException) e).getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else {
                msg = e.toString();
            }

            addAlternateMessage(mapping, request, null, msg);
        }

        try {
            tx.begin();

            prepareMethod((DynaValidatorForm) form, request, LIST, EDIT);

            tx.commit();
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured in second session, rollback", e);

            addAlternateMessage(mapping, request, null, e.toString());
        }
    } catch (Throwable e) {
        log.error("Exception occured while getting EntityManager: ", e);
        addAlternateMessage(mapping, request, null, e.toString());

    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }

    return getAlternateForward(mapping, request);
}

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

/**
 *
 * @param name/*from   w  ww.j  av a 2 s .c  o m*/
 * @param password
 * @return
 */
@Override
public User getByNameAndPassword(String name, String password) {
    EntityManager em = entityManagerFactory.createEntityManager();
    User user = null;
    boolean exists = false;

    try {
        em.getTransaction().begin();

        TypedQuery<User> query = em.createNamedQuery("User.findByUserLoginAndPassword", User.class);
        query.setParameter("login", name);
        query.setParameter("password", encryptionService.encrypt(password));

        user = query.getSingleResult();

        em.getTransaction().commit();
        exists = true;
    } catch (NoResultException ex) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(ex);
        exists = false;
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    if (exists) {
        return user;
    } else {
        return null;
    }

}

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  w  w w .  ja v  a 2  s.  c o 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:cz.muni.fi.dndtroops.test.TroopDaoImplTest.java

@Test
public void testUpdateGoldForTroop() {
    EntityManager entityManager = emf.createEntityManager();
    entityManager.getTransaction().begin();
    Troop troopC = new Troop();
    troopC.setName("Testers");
    troopC.setMoney(new BigDecimal("30"));
    entityManager.persist(troopC);/*from  ww  w . java  2 s  .  c  o m*/
    entityManager.getTransaction().commit();
    entityManager.close();

    troopDao.updateGoldForTroop(troopC.getId(), new BigDecimal("5"));

    Troop t1 = troopDao.findTroopById(troopC.getId());
    Assert.assertEquals(t1.getMoney().compareTo(new BigDecimal("5")), 0);

}