Java Code Examples for org.hibernate.Session.beginTransaction()

The following are Jave code examples for showing how to use beginTransaction() of the org.hibernate.Session class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: FlashBoard   File: AdminDaoImpl.java   Source Code and License Vote up 7 votes
@Override
public boolean approveUser(String username) {
	Boolean bool = false;
	Session session = HibernateUtil.getSession();
	Transaction tx = null;
	User myUser = udi.getUserByUsername(username);
	try {
		tx = session.beginTransaction();
		myUser.setApproved(true);
		session.update(myUser);
		tx.commit();
		bool = true;
		System.out.println("User: '" + username + "' successfully approved.");
	} catch (HibernateException he) {
		if (tx != null) {
			tx.rollback();
		}
	} finally {
		session.close();
	}
	return bool;
}
 
Example 2
Project: ImageClassify   File: CompositionService.java   Source Code and License Vote up 7 votes
/**
 *  持久化composition
 */
@Override
public boolean saveComp(Composition composition) {
	Session session = HibernateUtils.getSession(); //生成session实例
    Transaction tx = session.beginTransaction();  //创建transaction实例
    try {  
    	session.save(composition);    //使用session的sava方法将持久化对象保存到数据库中
		tx.commit();            //提交事务
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();          //回滚事务
		return false;
	}finally {
	  HibernateUtils.closeSession();  //关闭Session实例
	} 
}
 
Example 3
Project: TrabalhoCrisParte2   File: DAOCliente.java   Source Code and License Vote up 6 votes
public List listar() {
    Session session = DAOHibernateUtil.getSession();
    List listaCliente = null;
    try {
        session.beginTransaction();           
        listaCliente = session.createQuery("From Cliente").list();
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex);
    }
    finally{
        session.close();
        return listaCliente;
    }
}
 
Example 4
Project: ImageClassify   File: AdminService.java   Source Code and License Vote up 6 votes
/**
    * 
    */
@Override
public Admin findAdminByToken(String admin_token) {
	 Admin admin=null;
	 Session session=HibernateUtils.getSession();//生成Session实例
	 Transaction tx=session.beginTransaction();//生成事务实例
	 try {
		  admin=(Admin) session.createCriteria(Admin.class).add(Restrictions.eq("admin_token", admin_token)).uniqueResult();
		  tx.commit();
	     //调用session的get()方法,找到此用户到内存中 
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	}
	 return admin;
}
 
Example 5
Project: ImageClassify   File: CategoryService.java   Source Code and License Vote up 6 votes
/**
 * 根据类别id找到类别对象
 */
@Override
public Category findCategoryById(int category_id) {
	Category category = null;
	Session session = HibernateUtils.getSession();// 生成Session实例
	Transaction tx = session.beginTransaction();// 生成事务实例
	try {
		category = (Category) session.get(Category.class, category_id);
		tx.commit();// 提交事务
		// 调用session的get()方法,找到此用户到内存中
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();// 事务回滚
	} finally {
		HibernateUtils.closeSession();// 关闭session实例
	}
	return category;
}
 
Example 6
Project: ImageClassify   File: ContributeService.java   Source Code and License Vote up 6 votes
@Override
public int getAmountContributeOfAllByUser() { 
	Session session = HibernateUtils.getSession();
	Transaction tx = session.beginTransaction();
	String sql = "SELECT id,upload_img_time,upload_img_review_status,username,tel_num FROM user_contribute_img WHERE upload_img_review_status=0 ORDER BY upload_img_time ASC";
	List<Contribute_Img > cImgs = new ArrayList<Contribute_Img>();
	try { 
		cImgs = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
		tx.commit(); 
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	} finally {
		HibernateUtils.closeSession(); // 关闭Session实例
	} 
	return cImgs.size();
}
 
Example 7
Project: sjk   File: MergeServiceImpl.java   Source Code and License Vote up 6 votes
private Transaction batchIn1TransactionToApp(Session session, List<MarketApp> marketApps) {
    Transaction tx = null;
    try {
        session.setDefaultReadOnly(false);
        tx = session.beginTransaction();
        long start = System.currentTimeMillis();
        mergePaginationToApp(session, marketApps);
        session.flush();
        session.clear();
        logger.info("mergePaginationToApp耗时:{}", (System.currentTimeMillis() - start) + " ms!");
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        logger.error("Exception", e);
    }
    return tx;
}
 
Example 8
Project: OSWf-OSWorkflow-fork   File: HibernatePersistentVarsDAO.java   Source Code and License Vote up 6 votes
public Collection<String> getKeys(Long piid, String prefix, Type type) {

        if( piid == null)
            throw new PersistentVarsException("Could not find keys for 'null' piid");

        Session session = null;
        Transaction transaction = null;
        Collection<String> list = null;
        
        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            list = getKeysImpl(session, piid, prefix, type);

            transaction.commit();

        } catch (HibernateException hibernateException) {
            throw new PersistentVarsException("HibernatePropertySet.getKeys: " + hibernateException.getMessage());
        } finally {
            if (transaction != null && transaction.isActive())
                 transaction.rollback();

            if (session != null)
                session.close();
        } 

        return list;
    }
 
Example 9
Project: Hotel-Properties-Management-System   File: PaymentDaoImpl.java   Source Code and License Vote up 5 votes
@Override
public void beginTransactionIfAllowed(Session theSession) {
    if (!theSession.getTransaction().isActive()) {
        theSession.beginTransaction();
    } else {
        theSession.getTransaction().rollback();
        theSession.beginTransaction();
    }

}
 
Example 10
Project: Java_Good   File: HbConnectionTest.java   Source Code and License Vote up 5 votes
@Test
public void testHbConnection() {
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    List<UserData> result = session.createQuery("from UserData").list();

    for (UserData user : result) {
        System.out.println(user);
        //System.out.println(user.getUsers());
    }
    session.getTransaction().commit();
    session.close();


}
 
Example 11
Project: training-sample   File: HibernateOrderDao.java   Source Code and License Vote up 5 votes
@SuppressWarnings("unchecked")
@Override
public List<Order> findAll() {
	List<Order> orders = null;
	Session session = sessionFactory.getCurrentSession();
	try {
		session.beginTransaction();
		Query query = session.createQuery("from Order");
		orders = (List<Order>) query.list();
		session.getTransaction().commit();
	} catch (RuntimeException e) {
		session.getTransaction().rollback();
	}
	return orders;
}
 
Example 12
Project: hska-vis-legacy   File: RoleDAO.java   Source Code and License Vote up 5 votes
public Role getRoleByLevel(int roleLevel) {
	
	Role role = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
	try
	{
		session.beginTransaction();
           Criteria crit = session.createCriteria(Role.class);
           crit.add(Restrictions.eq("level",roleLevel));
           List<Role> resultList = crit.list();
           
           if (resultList.size() > 0) {
           	role = resultList.get(0);
           }
           session.getTransaction().commit();
           return role;
	}
	catch (HibernateException e)
	{
		System.out.println("Hibernate Exception" + e.getMessage());
		session.getTransaction().rollback();
		throw new RuntimeException(e);
	}

	

}
 
Example 13
Project: hibernate-springcache   File: EventManager.java   Source Code and License Vote up 5 votes
public List<String> listEmailsOfEvent(Long eventId) {
	Session session = sessionFactory.getCurrentSession();
	session.beginTransaction();

	List<String> emailList = new ArrayList<String>();
	Event event = session.load(Event.class, eventId);
	for (Iterator<Person> it = event.getParticipants().iterator(); it.hasNext(); ) {
		Person person = it.next();
		emailList.addAll(person.getEmailAddresses());
	}

	session.getTransaction().commit();
	return emailList;
}
 
Example 14
Project: ImageClassify   File: MarkService.java   Source Code and License Vote up 5 votes
@Override
public List<Mark> getMarkListByUserAndTask(int user_id, int img_id) {
	 List<Mark> marks = new ArrayList<Mark>();
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例 
	 try { 
		 marks = session.createSQLQuery("SELECT option_mark_name,manual_mark_name,mark_accuracy FROM mark WHERE user_id = "+user_id+" AND img_id = "+img_id).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	     //调用session的get()方法,找到此用户到内存中
	    tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();//事务回滚
	}finally{
		HibernateUtils.closeSession();//关闭session实例
	}     

	 List<Mark> marks2 = new ArrayList<Mark>(); 
	 
	 for (int i = 0; i < marks.size(); i++) { 
		  Mark mark = new Mark();
		  Map map = (Map) marks.get(i); 
		  mark.setOption_mark_name(map.get("option_mark_name")+"");
		  mark.setManual_mark_name(map.get("manual_mark_name")+""); 
		  mark.setMark_accuracy(map.get("mark_accuracy")+"");
		  marks2.add(mark);
	 }  
	 return marks2; 
}
 
Example 15
Project: maven_EWorld_OpenShift   File: Validate.java   Source Code and License Vote up 4 votes
synchronized public static boolean isUserEmailExists(String email)
{
         int chk=0;
         sf=Logic.getSf();
         Session s = null;
         List<Object> lst=new ArrayList<Object> ();
         try{
                s=sf.openSession();
                s.beginTransaction();
                Query qry=s.createQuery("select usr_id from UserDetails ud where ud.email_id=:eid");
                qry.setParameter("eid", email);
                lst=qry.getResultList();
                s.getTransaction().commit();
            }catch (Exception e)
                 {
                         chk=-1;
                         System.out.println("HibernateException Occured!!"+e);
                         e.printStackTrace();
                 }
            finally
                 {
                         if(s!=null)
                         {
                              s.clear();
                              s.close();
                         }
                 }
            if(chk==0)
            {
                  if (lst.isEmpty())
                  {
                        return (false);
                  }
                  else
                  {
                       return (true);
                  }
            }
            else
            {
                 return (true);
            }
}
 
Example 16
Project: crypto-bot   File: TestPersistence.java   Source Code and License Vote up 4 votes
/**
 * Test get open trades from order manager
 */
@Test
public void testGetOpenTrades() {
	
	final BitfinexApiBroker apiBroker = Mockito.mock(BitfinexApiBroker.class);
	final PortfolioOrderManager ordermanager = new PortfolioOrderManager(apiBroker);
	
	Assert.assertTrue(ordermanager.getAllOpenTrades().isEmpty());

	final Trade trade = new Trade("ABC", TradeDirection.LONG, BitfinexCurrencyPair.BTC_USD, 1);
	trade.setTradeState(TradeState.CREATED);
	
	final Session session = sessionFactory.openSession();
	
	session.beginTransaction();
	session.save(trade);
	session.getTransaction().commit();

	Assert.assertTrue(ordermanager.getAllOpenTrades().isEmpty());

	session.beginTransaction();
	trade.setTradeState(TradeState.OPEN);
	session.saveOrUpdate(trade);
	session.getTransaction().commit();
	
	session.beginTransaction();
	Assert.assertEquals(1, ordermanager.getAllOpenTrades().size());
	session.getTransaction().commit();
	
	final Trade trade2 = new Trade("ABC", TradeDirection.LONG, BitfinexCurrencyPair.BTC_USD, 1);
	trade2.setTradeState(TradeState.OPEN);
	session.beginTransaction();
	session.save(trade2);
	session.getTransaction().commit();
	
	session.beginTransaction();
	Assert.assertEquals(2, ordermanager.getAllOpenTrades().size());
	session.getTransaction().commit();
	
	session.close();
}
 
Example 17
Project: TrabalhoCrisParte2   File: DAOProduto.java   Source Code and License Vote up 4 votes
public void alterar(Produto produto) {

       Session session = DAOHibernateUtil.getSession();

       try {

           session.beginTransaction(); // Abre-se uma transação
           session.merge(produto);      // Acumula a operação de alteração do objeto produto no BD, na transação
           session.getTransaction().commit();   // Realiza definitivamente todas as operações pendentes na transação
           JOptionPane.showMessageDialog(null, "Produto alterado com sucesso");

       } catch (Exception ex) {
           JOptionPane.showMessageDialog(null, ex);

       }
   }
 
Example 18
Project: hibernate-ogm-ignite   File: ManyToOneTest.java   Source Code and License Vote up 4 votes
@Test
public void testBiDirManyToOneInsertUpdateFalse() throws Exception {
	final Session session = openSession();
	Transaction tx = session.beginTransaction();
	Beer hoegaarden = new Beer();
	Brewery hoeBrewery = new Brewery();
	hoeBrewery.getBeers().add( hoegaarden );
	hoegaarden.setBrewery( hoeBrewery );
	session.persist( hoeBrewery );
	tx.commit();
	session.clear();

	tx = session.beginTransaction();
	hoegaarden = get( session, Beer.class, hoegaarden.getId() );
	assertThat( hoegaarden ).isNotNull();
	assertThat( hoegaarden.getBrewery() ).isNotNull();
	assertThat( hoegaarden.getBrewery().getBeers() )
		.hasSize( 1 )
		.containsOnly( hoegaarden );
	Beer citron = new Beer();
	hoeBrewery = hoegaarden.getBrewery();
	hoeBrewery.getBeers().remove( hoegaarden );
	hoeBrewery.getBeers().add( citron );
	citron.setBrewery( hoeBrewery );
	session.delete( hoegaarden );
	tx.commit();

	session.clear();

	tx = session.beginTransaction();
	citron = get( session, Beer.class, citron.getId() );
	assertThat( citron.getBrewery().getBeers() )
		.hasSize( 1 )
		.containsOnly( citron );
	hoeBrewery = citron.getBrewery();
	citron.setBrewery( null );
	hoeBrewery.getBeers().clear();
	session.delete( citron );
	session.delete( hoeBrewery );
	tx.commit();

	session.close();

	checkCleanCache();
}
 
Example 19
Project: EBwn2_ForOpenShift   File: Validate.java   Source Code and License Vote up 4 votes
synchronized public static boolean isUserPasswordExists(String pass)
{
         int chk=0;
         sf=Logic.getSf();
         Session s = null;
         List<String> lst=new ArrayList<String> ();
         try{
                s=sf.openSession();
                s.beginTransaction();
                Query qry=s.createQuery("select usr_id from UserDetails ud where ud.pass=:pss");
                qry.setParameter("pss", pass);
                lst=qry.getResultList();
                s.getTransaction().commit();
            }catch (Exception e)
                 {
                         chk=-1;
                          System.out.println("HibernateException Occured!!"+e);
                         e.printStackTrace();
                 }
            finally
                 {
                         if(s!=null)
                         {
                              s.clear();
                              s.close();
                         }
                 }
            if(chk==0)
            {
                  if (lst.isEmpty())
                  {
                        return (false);
                  }
                  else
                  {
                       return (true);
                  }
            }
            else
            {
                 return (true);
            }
}
 
Example 20
Project: Library   File: LibraryServicesImpl.java   Source Code and License Vote up 3 votes
public RestResponse checkInBook(CheckInBook book) {

		RestResponse response = new RestResponse();
		Session session = this.sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		try {

			String paramString = "from BookLoan where book.ISBN='" + book.getIsbn() + "' and borrower.cardId="
					+ Integer.parseInt(book.getCardId());
			Query query = session.createQuery(paramString);

			BookLoan bookLoan = (BookLoan) query.uniqueResult();

			bookLoan.setDateIn(new Date());

			bookLoan.getBook().setAvailable(true);

			session.update(bookLoan);
			transaction.commit();

			response.setSuccess(true);
			response.setResult("Book Checked In Succesfully");
		} catch (Exception exception) {

			response.setSuccess(false);
			response.setError("Error Occurred. Try after some time");
			transaction.rollback();
		}

		session.close();

		return response;

	}