Java Code Examples for org.hibernate.Session#beginTransaction()
The following examples show how to use
org.hibernate.Session#beginTransaction() .
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Project File: CRUDTest.java License: Apache License 2.0 | 6 votes |
@Test public void stateTest(){ Configuration configuration = new Configuration(); configuration.configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); User user = new User(); // 瞬时态对象:没有持久化标识 OID,没有被 session 管理 user.setUsername("persistent"); Serializable id = session.save(user); // 这里是持久态对象:有持久化标识 OID,被 session 管理 transaction.commit(); session.close(); sessionFactory.close(); System.out.println(user); // 这里是托管态对象:有持久化标识 OID,没有被 session 管理 }
Example 2
Source Project: Project File: CRUDTest.java License: Apache License 2.0 | 6 votes |
@Test public void updateTest(){ Configuration configuration = new Configuration(); configuration.configure(); SessionFactory sessionFactory = configuration.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); User user = session.get(User.class, 1); user.setUsername("gjxaiou"); session.update(user); transaction.commit(); session.close(); sessionFactory.close(); }
Example 3
Source Project: ignite-book-code-samples File: EmpDaoImpl.java License: GNU General Public License v3.0 | 6 votes |
public void create(Integer empno, String ename, String job, Integer mgr) { Session session = sessionFactory.openSession(); session.beginTransaction(); Employee emp = new Employee(); emp.setEmpno(empno); emp.setEname(ename); emp.setJob(job); emp.setMgr(mgr); emp.setSal(1111); emp.setDeptno(10); emp.setDate(new Date(System.currentTimeMillis())); emp.setComm(111); session.save(emp); session.getTransaction().commit(); session.close(); }
Example 4
Source Project: kardio File: TestDaoService.java License: Apache License 2.0 | 6 votes |
public DaillyCompStatusEntity createDailyStatusEntity(String envName) { createHealthCheck(envName); Session session = sessionFactory.openSession(); Transaction trx = session.beginTransaction(); DaillyCompStatusEntity daillyCompStatusEntity = new DaillyCompStatusEntity(); daillyCompStatusEntity.setHealthCheck(session.get(HealthCheckEntity.class, new Integer(healthCheckID - 1))); StatusEntity se = new StatusEntity(); se.setStatusId(1); se.setStatusName("statusName"); session.save(se); daillyCompStatusEntity.setStatus(se); long date = System.currentTimeMillis(); daillyCompStatusEntity.setStatusDate(new java.sql.Date(date)); session.save(daillyCompStatusEntity); dailyCompStatusID++; trx.commit(); session.close(); return daillyCompStatusEntity; }
Example 5
Source Project: cacheonix-core File: ASTParserLoadingTest.java License: GNU Lesser General Public License v2.1 | 5 votes |
public void testSelectClauseImplicitJoinWithIterate() { Session s = openSession(); Transaction t = s.beginTransaction(); Zoo zoo = new Zoo(); zoo.setName("The Zoo"); zoo.setMammals( new HashMap() ); zoo.setAnimals( new HashMap() ); Mammal plat = new Mammal(); plat.setBodyWeight( 11f ); plat.setDescription( "Platypus" ); plat.setZoo(zoo); plat.setSerialNumber("plat123"); zoo.getMammals().put("Platypus", plat); zoo.getAnimals().put("plat123", plat); s.persist( plat ); s.persist(zoo); s.flush(); s.clear(); Query q = s.createQuery("select distinct a.zoo from Animal a where a.zoo is not null"); Type type = q.getReturnTypes()[0]; assertTrue( type instanceof ManyToOneType ); assertEquals( ( (ManyToOneType) type ).getAssociatedEntityName(), "org.hibernate.test.hql.Zoo" ); zoo = (Zoo) q .iterate().next(); assertEquals( zoo.getMammals().size(), 1 ); assertEquals( zoo.getAnimals().size(), 1 ); s.clear(); s.delete(plat); s.delete(zoo); t.commit(); s.close(); }
Example 6
Source Project: SensorWebClient File: HibernateUtil.java License: GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("unchecked") public static boolean otherAdminsExist(int userID) { Session session = getSessionFactory().getCurrentSession(); session.beginTransaction(); Criteria crit = session.createCriteria(User.class); List<User> users = crit.add(Restrictions.and(Restrictions.not(Restrictions.eq(ID, userID)), Restrictions.eq(ROLE, ADMIN))).list(); if (users.size() >= 1) { return true; } return false; }
Example 7
Source Project: Knowage-Server File: SbiMetaBcDAOHibImpl.java License: GNU Affero General Public License v3.0 | 5 votes |
/** * Modify a metatable. * * @param aMetaTable * the sbimetatable changed * * @throws EMFUserError * the EMF user error * * @see it.eng.spagobi.metadata.dao.ISbiMetaBcDAOHibImpl#modifyTable(SbiMetaTable) */ @Override public void modifyBc(SbiMetaBc aMetaBc) throws EMFUserError { logger.debug("IN"); Session tmpSession = null; Transaction tx = null; try { tmpSession = getSession(); tx = tmpSession.beginTransaction(); modifyBc(tmpSession, aMetaBc); tx.commit(); } catch (HibernateException he) { logException(he); if (tx != null) tx.rollback(); throw new EMFUserError(EMFErrorSeverity.ERROR, 100); } finally { if (tmpSession != null) { if (tmpSession.isOpen()) tmpSession.close(); } } logger.debug("OUT"); }
Example 8
Source Project: tutorials File: HibernateExceptionUnitTest.java License: MIT License | 5 votes |
@Test public void whenDeletingADeletedObject_thenOptimisticLockException() { thrown.expect(isA(OptimisticLockException.class)); thrown.expectMessage( "Batch update returned unexpected row count from update"); thrown.expectCause(isA(StaleStateException.class)); Session session = null; Transaction transaction = null; try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); Product product1 = new Product(); product1.setId(12); product1.setName("Product 12"); session.save(product1); transaction.commit(); session.close(); session = sessionFactory.openSession(); transaction = session.beginTransaction(); Product product2 = session.get(Product.class, 12); session.createNativeQuery("delete from Product where id=12") .executeUpdate(); // We need to refresh to fix the error. // session.refresh(product2); session.delete(product2); transaction.commit(); } catch (Exception e) { rollbackTransactionQuietly(transaction); throw (e); } finally { closeSessionQuietly(session); } }
Example 9
Source Project: Knowage-Server File: RememberMeDAOHibImpl.java License: GNU Affero General Public License v3.0 | 5 votes |
public List<RememberMe> getMyRememberMe(String userId) throws EMFInternalError { logger.debug("IN"); logger.debug("*** RememberMe - userId: "+ userId); Session aSession = null; Transaction tx = null; List toReturn = new ArrayList(); try { aSession = getSession(); tx = aSession.beginTransaction(); Criterion userIdCriterion = Expression.eq("userName", userId); Criteria criteria = aSession.createCriteria(SbiRememberMe.class); criteria.add(userIdCriterion); //criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List list = criteria.list(); Iterator it = list.iterator(); while (it.hasNext()) { SbiRememberMe hibObj = (SbiRememberMe) it.next(); toReturn.add(toRememberMe(hibObj)); } return toReturn; } catch (HibernateException he) { logException(he); if (tx != null) tx.rollback(); throw new EMFInternalError(EMFErrorSeverity.ERROR, "100"); } finally { if (aSession != null) { if (aSession.isOpen()) aSession.close(); } logger.debug("OUT"); } }
Example 10
Source Project: olat File: HibernateUtil.java License: Apache License 2.0 | 5 votes |
public static void save(final Object stat) { final Session session = getSession(); final Transaction transaction = session.beginTransaction(); try { session.save(stat); transaction.commit(); } finally { session.close(); } }
Example 11
Source Project: cacheonix-core File: OrphanTest.java License: GNU Lesser General Public License v2.1 | 5 votes |
public void testOrphanDeleteOnDelete() { Session session = openSession(); Transaction t = session.beginTransaction(); Product prod = new Product(); prod.setName("Widget"); Part part = new Part(); part.setName("Widge"); part.setDescription("part if a Widget"); prod.getParts().add(part); Part part2 = new Part(); part2.setName("Get"); part2.setDescription("another part if a Widget"); prod.getParts().add(part2); session.persist(prod); session.flush(); prod.getParts().remove(part); session.delete(prod); t.commit(); session.close(); session = openSession(); t = session.beginTransaction(); assertNull( session.get(Part.class, "Widge") ); assertNull( session.get(Part.class, "Get") ); assertNull( session.get(Product.class, "Widget") ); t.commit(); session.close(); }
Example 12
Source Project: Knowage-Server File: MenuDAOImpl.java License: GNU Affero General Public License v3.0 | 5 votes |
/** * Load menu by name. * * @param name the name * * @return the menu * * @throws EMFUserError the EMF user error * * @see it.eng.spagobi.wapp.dao.IMenuDAO#loadMenuByName(string) */ @Override public Menu loadMenuByName(String name) throws EMFUserError { Menu biMenu = null; Session tmpSession = null; Transaction tx = null; try { tmpSession = getSession(); tx = tmpSession.beginTransaction(); Criterion labelCriterrion = Expression.eq("name", name); Criteria criteria = tmpSession.createCriteria(SbiMenu.class); criteria.add(labelCriterrion); SbiMenu hibMenu = (SbiMenu) criteria.uniqueResult(); if (hibMenu == null) return null; biMenu = toMenu(hibMenu, null); // tx.commit(); } catch (HibernateException he) { logException(he); if (tx != null) tx.rollback(); throw new EMFUserError(EMFErrorSeverity.ERROR, 100); } finally { if (tmpSession != null) { if (tmpSession.isOpen()) tmpSession.close(); } } return biMenu; }
Example 13
Source Project: core File: ApiKey.java License: GNU General Public License v3.0 | 5 votes |
/** * Deletes this ApiKey from specified database * * @param dbName name of database */ public void deleteApiKey(String dbName) { Session session = HibernateUtils.getSession(dbName); try { Transaction transaction = session.beginTransaction(); session.delete(this); transaction.commit(); } catch (Exception e) { throw e; } finally { // Make sure that the session always gets closed, even if // exception occurs session.close(); } }
Example 14
Source Project: judgels File: HibernateSessionExtension.java License: GNU General Public License v2.0 | 5 votes |
private void openSession(SessionFactory sessionFactory, ExtensionContext context) { Session session = sessionFactory.openSession(); Transaction txn = session.beginTransaction(); ManagedSessionContext.bind(session); SessionContext sessionContext = new SessionContext(sessionFactory, session, txn); getStore(context).put(context.getUniqueId(), sessionContext); }
Example 15
Source Project: Knowage-Server File: MenuDAOImpl.java License: GNU Affero General Public License v3.0 | 5 votes |
@Override public SbiMenu loadSbiMenubyName(String name) { Session tmpSession = null; Transaction tx = null; try { tmpSession = getSession(); tx = tmpSession.beginTransaction(); Criterion domainCdCriterrion = Expression.eq("name", name); Criteria criteria = tmpSession.createCriteria(SbiMenu.class); criteria.add(domainCdCriterrion); SbiMenu hibMenu = (SbiMenu) criteria.uniqueResult(); return hibMenu; } catch (HibernateException he) { logException(he); if (tx != null) tx.rollback(); } finally { if (tmpSession != null) { if (tmpSession.isOpen()) tmpSession.close(); } } return null; }
Example 16
Source Project: crypto-bot File: TestPersistence.java License: Apache License 2.0 | 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
Source Project: Knowage-Server File: ProgressThreadDAOImpl.java License: GNU Affero General Public License v3.0 | 4 votes |
@Override public Integer insertProgressThread(ProgressThread progThread) throws EMFUserError { // logger.debug("IN"); Session aSession = null; Transaction tx = null; SbiProgressThread sbiPT = null; try { aSession = getSession(); tx = aSession.beginTransaction(); sbiPT = new SbiProgressThread(); sbiPT.setFunctionCd(progThread.getFunctionCd()); sbiPT.setUserId(progThread.getUserId()); sbiPT.setTotal(progThread.getTotal()); sbiPT.setPartial(0); sbiPT.setStatus(PREPARED); sbiPT.setType(progThread.getType()); sbiPT.setRandomKey(progThread.getRandomKey()); aSession.save(sbiPT); tx.commit(); } catch (HibernateException he) { logger.error( "Error while inserting the progress thread with user id " + progThread.getUserId() + " and on functionality " + progThread.getFunctionCd(), he); if (tx != null) tx.rollback(); throw new EMFUserError(EMFErrorSeverity.ERROR, 100); } finally { if (aSession != null) { if (aSession.isOpen()) aSession.close(); // logger.debug("OUT"); } } // logger.debug("OUT"); return sbiPT.getProgressThreadId(); }
Example 18
Source Project: Knowage-Server File: ParameterDAOHibImpl.java License: GNU Affero General Public License v3.0 | 4 votes |
/** * Modify parameter. * * @param aParameter * the a parameter * * @throws EMFUserError * the EMF user error * * @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IParameterDAO#modifyParameter(it.eng.spagobi.behaviouralmodel.analyticaldriver.bo.Parameter) */ @Override public void modifyParameter(Parameter aParameter) throws EMFUserError { Session aSession = null; Transaction tx = null; try { aSession = getSession(); tx = aSession.beginTransaction(); String[] info = aParameter.getModality().split(","); List<String> list = Arrays.asList(info); String input_type_cd = null; String input_type_id = null; Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { input_type_cd = iterator.next(); input_type_id = iterator.next(); } Integer typeId = Integer.valueOf(input_type_id); SbiDomains parameterType = (SbiDomains) aSession.load(SbiDomains.class, typeId); SbiParameters hibParameters = (SbiParameters) aSession.load(SbiParameters.class, aParameter.getId()); updateSbiCommonInfo4Update(hibParameters); hibParameters.setDescr(aParameter.getDescription()); hibParameters.setLength(new Short(aParameter.getLength().shortValue())); hibParameters.setLabel(aParameter.getLabel()); hibParameters.setName(aParameter.getName()); hibParameters.setParameterTypeCode(input_type_cd); hibParameters.setMask(aParameter.getMask()); hibParameters.setParameterType(parameterType); hibParameters.setValueSelection(aParameter.getValueSelection()); hibParameters.setSelectedLayer(aParameter.getSelectedLayer()); hibParameters.setSelectedLayerProp(aParameter.getSelectedLayerProp()); if (aParameter.isFunctional()) hibParameters.setFunctionalFlag(new Short((short) 1)); else hibParameters.setFunctionalFlag(new Short((short) 0)); if (aParameter.isTemporal()) hibParameters.setTemporalFlag(new Short((short) 1)); else hibParameters.setTemporalFlag(new Short((short) 0)); tx.commit(); } catch (HibernateException he) { logException(he); if (tx != null) tx.rollback(); throw new EMFUserError(EMFErrorSeverity.ERROR, 100); } finally { if (aSession != null) { if (aSession.isOpen()) aSession.close(); } } }
Example 19
Source Project: Knowage-Server File: WhatifWorkflowDAOHibImpl.java License: GNU Affero General Public License v3.0 | 4 votes |
@Override public void updateWorkflow(List<SbiWhatifWorkflow> workflow, int mId) { logger.debug("IN"); Session aSession = null; Transaction tx = null; List<Integer> existing = getWorkflowUsersOfModel(mId); List<Integer> toRemove = toRemove(workflow, existing); List<Integer> toAdd = toAdd(workflow, existing); List<SbiWhatifWorkflow> wfToAdd = new ArrayList<>(); if (toRemove.size() > 0) removeUsersForUpdate(toRemove, mId); try { aSession = getSession(); tx = aSession.beginTransaction(); for (int i = 0; i < workflow.size(); i++) { if (!toAdd.contains(workflow.get(i).getUserId())) { SbiWhatifWorkflow wf = workflow.get(i); wf.setSequcence(i); updateSbiCommonInfo4Update(wf); aSession.update(wf); } else { wfToAdd.add(workflow.get(i)); } } tx.commit(); } catch (HibernateException he) { logger.error(he.getMessage(), he); if (tx != null) tx.rollback(); } finally { if (aSession != null) { if (aSession.isOpen()) aSession.close(); } if (!wfToAdd.isEmpty()) createNewWorkflow(wfToAdd); } }
Example 20
Source Project: cacheonix-core File: MixedTest.java License: GNU Lesser General Public License v2.1 | 4 votes |
public void testMixedInheritance() { Session s = openSession( new DocumentInterceptor() ); Transaction t = s.beginTransaction(); Folder f = new Folder(); f.setName( "/" ); s.save( f ); Document d = new Document(); d.setName( "Hibernate in Action" ); d.setContent( Hibernate.createBlob( "blah blah blah".getBytes() ) ); d.setParent( f ); Long did = (Long) s.save( d ); SecureDocument d2 = new SecureDocument(); d2.setName( "Secret" ); d2.setContent( Hibernate.createBlob( "wxyz wxyz".getBytes() ) ); d2.setPermissionBits( (byte) 664 ); d2.setOwner( "gavin" ); d2.setParent( f ); Long d2id = (Long) s.save( d2 ); t.commit(); s.close(); if ( getDialect() instanceof PostgreSQLDialect ) return; s = openSession( new DocumentInterceptor() ); t = s.beginTransaction(); Item id = (Item) s.load( Item.class, did ); assertEquals( did, id.getId() ); assertEquals( "Hibernate in Action", id.getName() ); assertEquals( "/", id.getParent().getName() ); Item id2 = (Item) s.load( Item.class, d2id ); assertEquals( d2id, id2.getId() ); assertEquals( "Secret", id2.getName() ); assertEquals( "/", id2.getParent().getName() ); id.setName( "HiA" ); d2 = (SecureDocument) s.load( SecureDocument.class, d2id ); d2.setOwner( "max" ); s.flush(); s.clear(); d = (Document) s.load( Document.class, did ); assertEquals( did, d.getId() ); assertEquals( "HiA", d.getName() ); assertNotNull( d.getContent() ); assertEquals( "/", d.getParent().getName() ); assertNotNull( d.getCreated() ); assertNotNull( d.getModified() ); d2 = (SecureDocument) s.load( SecureDocument.class, d2id ); assertEquals( d2id, d2.getId() ); assertEquals( "Secret", d2.getName() ); assertNotNull( d2.getContent() ); assertEquals( "max", d2.getOwner() ); assertEquals( "/", d2.getParent().getName() ); assertEquals( (byte) 664, d2.getPermissionBits() ); assertNotNull( d2.getCreated() ); assertNotNull( d2.getModified() ); s.delete( d.getParent() ); s.delete( d ); s.delete( d2 ); t.commit(); s.close(); }