Java 类javax.persistence.EntityTransaction 实例源码

项目:bibliometrics    文件:RolePermissionDAO.java   
/**
 * retrieves the <code>RolesPermission</code> by the role.
 * 
 * @param role
 *            the role
 * @return userPermissions the list of permissions of the user
 * 
 */
public static Set<String> getPermission(String role) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<RolePermission> q = cb.createQuery(RolePermission.class);
    Root<RolePermission> c = q.from(RolePermission.class);
    q.select(c).where(cb.equal(c.get("roleName"), role));
    TypedQuery<RolePermission> query = em.createQuery(q);
    List<RolePermission> permissions = query.getResultList();
    Set<String> userPermissions = new HashSet<String>();
    for (RolePermission permission : permissions)
        userPermissions.add(permission.getPermission());
    tx.commit();
    em.close();
    return userPermissions;
}
项目:full-javaee-app    文件:WeeklyStatsDataAccessObject.java   
public static WeeklyStats persist (WeeklyStats stats) {
    if (stats != null) {
           EntityManager em = EMFUtil.getEMFactory().createEntityManager();
           EntityTransaction trans = em.getTransaction();
           try {
               trans.begin();
               em.persist(stats);
               trans.commit();
               return stats;
           } catch (Exception e) {
               e.printStackTrace();
               trans.rollback();
           } finally {
               em.close();
           }
    }
    return null;
}
项目:bdf2    文件:TaskServiceImpl.java   
public void changeTaskOwner(long taskId, String newOwner) {
    Task task=this.getTask(taskId);
    if(task.getStatus().equals(TaskStatus.Created)){
        EntityManager em=getEntityManager();
        EntityTransaction trans=em.getTransaction();
        try{
            trans.begin();
            task.setOwner(newOwner);
            em.persist(task);
            trans.commit();
        }catch(Exception ex){
            trans.rollback();
            throw new RuntimeException(ex);
        }
    }else{
        throw new IllegalStateException("Current task status is "+task.getStatus()+",can not change it owner!");
    }
}
项目:marathonv5    文件:DataAppLoader.java   
/**
 * @param args the command line arguments
 */
@PersistenceUnit
public static void main(String[] args) {
    System.out.println("Creating entity information...");
    EntityManager entityManager = Persistence.createEntityManagerFactory("DataAppLibraryPULocal").createEntityManager();
    EntityTransaction et = entityManager.getTransaction();
    et.begin();
    loadDiscountRate(entityManager);
    loadRegion(entityManager);
    loadRole(entityManager);
    loadTransmission(entityManager);
    loadProductType(entityManager);
    loadEngine(entityManager);
    loadProduct(entityManager);
    et.commit();


    EntityManager specialEntityManager = new InitialLoadEntityManagerProxy(entityManager);
    SalesSimulator simulator = new SalesSimulator(specialEntityManager);
    Calendar cal = Calendar.getInstance();
    int year = cal.get(Calendar.YEAR);
    cal.clear();
    cal.set(year-1, 0, 1, 0, 0, 0); // go back to begining of year, 3 years ago
    System.out.println("Creating historical data...");
    System.out.println("        This may take 5 to 15min depending on machine speed.");
    simulator.run(cal.getTime(), new Date());

    entityManager.close();
}
项目:LivroJavaComoProgramar10Edicao    文件:AddressBook.java   
private void insertButtonActionPerformed(ActionEvent evt) 
{
   Addresses address = new Addresses();
   address.setFirstname(firstNameTextField.getText());
   address.setLastname(lastNameTextField.getText());
   address.setPhonenumber(phoneTextField.getText());
   address.setEmail(emailTextField.getText());

   // get an EntityTransaction to manage insert operation
   EntityTransaction transaction = entityManager.getTransaction();

   try
   {
      transaction.begin(); // start transaction
      entityManager.persist(address); // store new entry
      transaction.commit(); // commit changes to the database
      JOptionPane.showMessageDialog(this, "Person added!",
         "Person added", JOptionPane.PLAIN_MESSAGE);
   }
   catch (Exception e) // if transaction failed
   {
      transaction.rollback(); // undo database operations 
      JOptionPane.showMessageDialog(this, "Person not added!",
         e.getMessage(), JOptionPane.PLAIN_MESSAGE);
   }
}
项目:osc-core    文件:TestTransactionControl.java   
private <T> T runInTran(Callable<T> arg0) {
    EntityTransaction tx = this.em.getTransaction();
    try {
        tx.begin();
        T o = arg0.call();
        tx.commit();

        callListeners(TransactionStatus.COMMITTED);

        return o;
    } catch (Exception e) {
        tx.rollback();
        callListeners(TransactionStatus.ROLLED_BACK);
        if(e instanceof ScopedWorkException) {
            throw (ScopedWorkException) e;
        }
        throw new ScopedWorkException("The work failed", e, getCurrentContext());
    } finally {
        this.txActive.compareAndSet(true, false);
        this.context.clear();
        this.em.clear();
    }
}
项目:testing_security_development_enterprise_systems    文件:NotStandardTest.java   
private boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
项目:testing_security_development_enterprise_systems    文件:UserTest.java   
private boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
项目:testing_security_development_enterprise_systems    文件:UserTest.java   
private boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
项目:testing_security_development_enterprise_systems    文件:UserTest.java   
private boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
项目:testing_security_development_enterprise_systems    文件:TransactionExecutor.java   
private Thread createThread(Consumer<EntityManager> command) {

        return new Thread(() ->{
            EntityManager em = factory.createEntityManager();
            EntityTransaction tx = em.getTransaction();

            tx.begin();
            try{
                command.accept(em);
                tx.commit();
            } catch (Exception e){
                tx.rollback();
                System.out.println("\n\nFailed transaction on separated thread: "+e.getCause().toString()+"\n\n");
            }
            em.close();
        });
    }
项目:testing_security_development_enterprise_systems    文件:EntityTestBase.java   
protected boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for (Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
项目:testing_security_development_enterprise_systems    文件:QuizEntityTest.java   
@Test
public void testQuiz(){

    Quiz quiz = new Quiz();
    quiz.setQuestion("Will this test pass?");
    quiz.setFirstAnswer("Yes");
    quiz.setSecondAnswer("No");
    quiz.setThirdAnswer("Maybe");
    quiz.setFourthAnswer("No idea");
    quiz.setIndexOfCorrectAnswer(0);

    EntityManagerFactory factory = Persistence.createEntityManagerFactory("DB");
    EntityManager em = factory.createEntityManager();

    EntityTransaction tx = em.getTransaction();
    tx.begin();

    em.persist(quiz);

    tx.commit();
}
项目:testing_security_development_enterprise_systems    文件:EntityTestBase.java   
protected boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
项目:testing_security_development_enterprise_systems    文件:EntityTestBase.java   
protected boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
项目:testing_security_development_enterprise_systems    文件:EntityTestBase.java   
protected boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
项目:testing_security_development_enterprise_systems    文件:EntityTestBase.java   
protected boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
项目:lams    文件:JpaTransactionManager.java   
@Override
protected void doRollback(DefaultTransactionStatus status) {
    JpaTransactionObject txObject = (JpaTransactionObject) status.getTransaction();
    if (status.isDebug()) {
        logger.debug("Rolling back JPA transaction on EntityManager [" +
                txObject.getEntityManagerHolder().getEntityManager() + "]");
    }
    try {
        EntityTransaction tx = txObject.getEntityManagerHolder().getEntityManager().getTransaction();
        if (tx.isActive()) {
            tx.rollback();
        }
    }
    catch (PersistenceException ex) {
        throw new TransactionSystemException("Could not roll back JPA transaction", ex);
    }
    finally {
        if (!txObject.isNewEntityManagerHolder()) {
            // Clear all pending inserts/updates/deletes in the EntityManager.
            // Necessary for pre-bound EntityManagers, to avoid inconsistent state.
            txObject.getEntityManagerHolder().getEntityManager().clear();
        }
    }
}
项目:bdf2    文件:TaskServiceImpl.java   
private void changeTask(long taskId,String username,StatusOperation operation,String faultMessage) {
    EntityManager em=getEntityManager();
    EntityTransaction trans=em.getTransaction();
    try{
        trans.begin();
        Task task=em.find(Task.class, taskId);
        if(StringUtils.isNotEmpty(faultMessage)){
            task.setFaultMessage(faultMessage);
        }
        if(changeTaskStatus(task,operation)){
            em.persist(task);               
        }
        TaskStatus status=task.getStatus();
        if(status.equals(TaskStatus.Completed) || status.equals(TaskStatus.Error) || status.equals(TaskStatus.Exited) || status.equals(TaskStatus.Obsolete) || status.equals(TaskStatus.Failed)){
            StatefulKnowledgeSession session=this.bpmService.getSession(task.getSessionId());
            session.getWorkItemManager().completeWorkItem(task.getWorkItemId(),null);   
            session.dispose();
        }
        trans.commit();
    }catch(Exception ex){
        trans.rollback();
        throw new RuntimeException(ex);
    }
}
项目:bibliometrics    文件:UserDAO.java   
public static User getUser(String username) {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("userData");
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<User> q = cb.createQuery(User.class);
    Root<User> c = q.from(User.class);
    q.select(c).where(cb.equal(c.get("username"), username));
    TypedQuery<User> query = em.createQuery(q);
    List<User> users = query.getResultList();
    em.close();
    LOGGER.info("found " + users.size() + " users with username " + username);
    if (users.size() == 1)
        return users.get(0);
    else
        return null;
}
项目:server-vot    文件:JPARepository.java   
@Override
public Optional<MODEL> update(MODEL model) throws RuntimeException {
    checkModelNullity(model);

    Optional<MODEL> possibleModel = findById(model.getId());
    possibleModel.ifPresent(found -> {
        try {
            checkIfCollides(model);

            EntityTransaction tr = em.getTransaction();
            tr.begin();
            found.updateWith(model);
            tr.commit();
        } finally {
            em.detach(found);
        }
    });

    return possibleModel;
}
项目:dashboard1b    文件:InsertP.java   
@Override
public List<CitizenDB> insert(List<CitizenDB> citizens) throws SQLException {
    EntityManager em = Jpa.createEntityManager();
    EntityTransaction trx = em.getTransaction();
    trx.begin();
    List<CitizenDB> users = new ArrayList<CitizenDB>();
    try{

        for(CitizenDB citizen : citizens)
            if(checkCitizen.checkCitizenInformation(citizen) && checkCitizen(citizen)){
                citizen.setPassword(generationPassword.passwordGenerator());
                Jpa.getManager().persist(citizen);
                users.add(citizen);
            }

    trx.commit();       
    }catch(RuntimeException e){
        trx.rollback();
        throw e;
    }
    finally{
        em.close();
    }
    return users;
}
项目:dashboard1b    文件:DataBaseTest.java   
private int numberCitizen(){
    EntityManager em = Jpa.createEntityManager();
    EntityTransaction trx = em.getTransaction();
    trx.begin();
    try{

        Query query = Jpa.getManager().createQuery("select c from CitizenDB c");
        return query.getResultList().size();

    }catch(RuntimeException e){
        trx.rollback();
        throw e;
    }
    finally{
        em.close();
    }
}
项目:full-javaee-app    文件:ConversationMessageDataAccessObject.java   
public static ConversationMessages merge (ConversationMessages message) {
    if (message != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            message = em.merge(message);
            trans.commit();
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:ConversationMessageDataAccessObject.java   
public static ConversationMessages persist (ConversationMessages message) {
    if (message != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(message);
            trans.commit();
            return message;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:ConversationMessageDataAccessObject.java   
public static boolean delete(int messageID) {
    if (messageID > 0) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        ConversationMessages message = em.find(ConversationMessages.class, messageID);
        if (message != null) {
            EntityTransaction trans = em.getTransaction();
            try {
                trans.begin();
                em.remove(message);
                trans.commit();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                trans.rollback();
            } finally {
                em.close();
            }
        }
    }
    return false;
}
项目:full-javaee-app    文件:ConversationDataAccessObject.java   
public static Conversations merge (Conversations conversation) {
    if (conversation != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            conversation = em.merge(conversation);
            trans.commit();
            return conversation;
        } catch (Exception e) {
            trans.rollback();
            e.printStackTrace();
            return null;
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:ConversationDataAccessObject.java   
public static Conversations persist (Conversations conversation) {
    if (conversation != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(conversation);
            trans.commit();
            return conversation;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:ConversationDataAccessObject.java   
public static boolean delete(int conversationID) {
    if (conversationID > 0) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        Conversations conversation = em.find(Conversations.class, conversationID);
        if (conversation != null) {
            EntityTransaction trans = em.getTransaction();
            try {
                trans.begin();
                em.remove(conversation);
                trans.commit();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                trans.rollback();
            } finally {
                em.close();
            }
        }
    }
    return false;
}
项目:full-javaee-app    文件:ProfileViewDataAccessObject.java   
public static ProfileViews merge (ProfileViews view) {
    if (view != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            view = em.merge(view);
            trans.commit();
            return view;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:ProfileViewDataAccessObject.java   
public static ProfileViews persist (ProfileViews view) {
    if (view != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(view);
            trans.commit();
            return view;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:ReceivedTextDataAccessObject.java   
public static ReceivedTexts persist(ReceivedTexts text) {
    if (text != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(text);
            trans.commit();
            return text;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:ReceivedTextDataAccessObject.java   
public static ReceivedTexts merge(ReceivedTexts text) {
    if (text != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            text = em.merge(text);
            trans.commit();
            return text;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:CandidatePersistence.java   
public static CandidateLoginLogs addLoginLog(Candidates candidate) {
    if (candidate != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        CandidateLoginLogs loginLog = new CandidateLoginLogs(candidate.getCandidateID(), Clock.getCurrentDate(),
                Clock.getCurrentTime());
        loginLog.setCandidateID(candidate.getCandidateID());
        try {
            trans.begin();
            em.persist(loginLog);
            trans.commit();
            loginLog.setCandidate(candidate);
            return loginLog;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        }
    }
    return null;
}
项目:full-javaee-app    文件:CandidatePersistence.java   
public static Candidates persist(Candidates candidate) {
    if (candidate != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(candidate);
            trans.commit();
            return candidate;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:CandidatePersistence.java   
public static Candidates merge(Candidates candidate) {
    if (candidate != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            candidate = em.merge(candidate);
            trans.commit();
            return candidate;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:CandidatePersistence.java   
public static boolean delete(int candidateID) {
    if (candidateID > 0) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        Candidates candidate = em.find(Candidates.class, candidateID);
        if (candidate != null) {
            EntityTransaction trans = em.getTransaction();
            try {
                trans.begin();
                em.remove(candidate);
                trans.commit();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                trans.rollback();
            } finally {
                em.close();
            }
        }
    }
    return false;
}
项目:full-javaee-app    文件:CandidatePersistence.java   
public static CandidateActivityLogs addActivityLog(CandidateActivityLogs activityLog) {
    if (activityLog != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(activityLog);
            trans.commit();
            return activityLog;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        } finally {
            em.close();
        }
    }
    return null;
}
项目:full-javaee-app    文件:ClientPipelineDataAccessObject.java   
public static ClientPipelines persist (ClientPipelines elt) {
    if (elt != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            em.persist(elt);
            trans.commit();
            return elt;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
        }
    }
    return null;
}
项目:full-javaee-app    文件:CompanyDataAccessObject.java   
public static Companies merge(Companies company) {
    if (company != null) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        EntityTransaction trans = em.getTransaction();
        try {
            trans.begin();
            company = em.merge(company);
            trans.commit();
            return company;
        } catch (Exception e) {
            e.printStackTrace();
            trans.rollback();
            return null;
        } finally {
            em.close();
        }
    }
    return null;
}