org.hibernate.Session#beginTransaction ( )源码实例Demo

下面列出了org.hibernate.Session#beginTransaction ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: Project   文件: CRUDTest.java
@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 管理
}
 
源代码2 项目: Project   文件: CRUDTest.java
@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();
}
 
源代码3 项目: ignite-book-code-samples   文件: EmpDaoImpl.java
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();
}
 
源代码4 项目: kardio   文件: TestDaoService.java
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;
}
 
源代码5 项目: cacheonix-core   文件: ASTParserLoadingTest.java
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();
}
 
源代码6 项目: SensorWebClient   文件: HibernateUtil.java
@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;
}
 
源代码7 项目: Knowage-Server   文件: SbiMetaBcDAOHibImpl.java
/**
 * 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");

}
 
源代码8 项目: tutorials   文件: HibernateExceptionUnitTest.java
@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);
    }
}
 
源代码9 项目: Knowage-Server   文件: RememberMeDAOHibImpl.java
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");
	}
}
 
源代码10 项目: olat   文件: HibernateUtil.java
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();
    }
}
 
源代码11 项目: cacheonix-core   文件: OrphanTest.java
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();
}
 
源代码12 项目: Knowage-Server   文件: MenuDAOImpl.java
/**
 * 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;
}
 
源代码13 项目: core   文件: ApiKey.java
/**
 * 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();
	}
}
 
源代码14 项目: judgels   文件: HibernateSessionExtension.java
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);
}
 
源代码15 项目: Knowage-Server   文件: MenuDAOImpl.java
@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;
}
 
源代码16 项目: crypto-bot   文件: TestPersistence.java
/**
 * 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();
}
 
源代码17 项目: Knowage-Server   文件: ProgressThreadDAOImpl.java
@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();
}
 
源代码18 项目: Knowage-Server   文件: ParameterDAOHibImpl.java
/**
 * 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();
		}
	}

}
 
源代码19 项目: Knowage-Server   文件: WhatifWorkflowDAOHibImpl.java
@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);
	}
}
 
源代码20 项目: cacheonix-core   文件: MixedTest.java
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();
}