下面列出了org.hibernate.Transaction#isActive ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private int saveSbiFederationDefinition(FederationDefinition dataset, boolean duplicated) {
LogMF.debug(logger, "IN: model = [{0}]", dataset);
Session session = null;
Transaction transaction = null;
try {
session = getSession();
Assert.assertNotNull(session, "session cannot be null");
transaction = session.beginTransaction();
int id = saveSbiFederationDefinition(dataset, duplicated, session, transaction).getFederation_id();
transaction.commit();
return id;
} catch (Throwable t) {
logException(t);
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw new SpagoBIDAOException("An unexpected error occured while saving model [" + dataset + "]", t);
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
}
@Override
public Integer insert(SbiUdpValue propValue) {
logger.debug("IN");
Session session = null;
Transaction tx = null;
Integer id = null;
try {
session = getSession();
tx = session.beginTransaction();
updateSbiCommonInfo4Insert(propValue);
id = (Integer) session.save(propValue);
tx.commit();
} catch (HibernateException e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw e;
} finally {
if (session != null) {
session.close();
}
logger.debug("OUT");
}
return id;
}
@Override
public void update(SbiUdpValue propValue) {
logger.debug("IN");
Session session = getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
updateSbiCommonInfo4Update(propValue);
session.update(propValue);
tx.commit();
} catch (HibernateException e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
logger.debug("OUT");
}
@SuppressWarnings("unchecked")
public List<SbiUdp> findAll() {
Session session = getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List<SbiUdp> list = (List<SbiUdp>)session.createQuery("from SbiUdp").list();
tx.commit();
return list;
} catch (HibernateException e) {
if( tx != null && tx.isActive() ){
tx.rollback();
}
throw e;
}finally{
session.close();
}
}
@Override
@SuppressWarnings("unchecked")
public SbiUdpValue findById(Integer id) {
logger.debug("IN");
SbiUdpValue propValue = null;
Session session = getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
propValue = (SbiUdpValue) session.get(SbiUdpValue.class, id);
tx.commit();
} catch (HibernateException e) {
if (tx != null && tx.isActive()) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
logger.debug("OUT");
return propValue;
}
protected void doInTransaction(HibernateTransactionConsumer callable) {
Session session = null;
Transaction txn = null;
try {
session = getSessionFactory().openSession();
callable.beforeTransactionCompletion();
txn = session.beginTransaction();
callable.accept(session);
txn.commit();
} catch (RuntimeException e) {
if ( txn != null && txn.isActive() ) txn.rollback();
throw e;
} finally {
callable.afterTransactionCompletion();
if (session != null) {
session.close();
}
}
}
@Test
public void test() {
Session session = null;
Transaction txn = null;
try {
session = sf.openSession();
txn = session.beginTransaction();
SecurityId securityId = new SecurityId();
securityId.setRole("Role");
session.persist(securityId);
txn.commit();
} catch (RuntimeException e) {
if ( txn != null && txn.isActive() ) txn.rollback();
throw e;
} finally {
if (session != null) {
session.close();
}
}
}
/** {@inheritDoc} */
@Override public void onSessionEnd(CacheStoreSession ses, boolean commit) {
Session hibSes = ses.attach(null);
if (hibSes != null) {
try {
Transaction tx = hibSes.getTransaction();
if (commit) {
hibSes.flush();
if (tx.isActive())
tx.commit();
}
else if (tx.isActive())
tx.rollback();
}
catch (HibernateException e) {
throw new CacheWriterException("Failed to end store session [tx=" + ses.transaction() + ']', e);
}
finally {
hibSes.close();
}
}
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
super.afterTest();
Session s = store.session(null);
if (s == null)
return;
try {
s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
.setFlushMode(FlushMode.ALWAYS).executeUpdate();
Transaction hTx = s.getTransaction();
if (hTx != null && hTx.isActive())
hTx.commit();
}
finally {
s.close();
}
}
public void delete(SbiUdp prop) {
logger.debug("IN");
Session session = getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.delete(prop);
tx.commit();
} catch (HibernateException e) {
if( tx != null && tx.isActive() ){
tx.rollback();
}
throw e;
}finally{
session.close();
}
logger.debug("OUT");
}
@Override
public SbiCatalogFunction getCatalogFunctionByLabel(String label) {
Session session;
Transaction transaction = null;
SbiCatalogFunction sbiCatalogFunction = null;
logger.debug("IN");
session = null;
try {
session = getSession();
Assert.assertNotNull(session, "session cannot be null");
transaction = session.beginTransaction();
String hql = "FROM SbiCatalogFunction F WHERE F.label = ?";
Query query = session.createQuery(hql);
query.setString(0, label);
sbiCatalogFunction = (SbiCatalogFunction) query.uniqueResult();
transaction.commit();
} catch (Throwable t) {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw new SpagoBIDAOException("An error occured while reading Catalog Functions from DB", t);
} finally {
if (session != null && session.isOpen()) {
session.close();
}
logger.debug("OUT");
}
return sbiCatalogFunction;
}
public void commitIfActiveAndClose(Transaction tx, Session aSession) {
if (tx != null && tx.isActive()) {
tx.commit();
}
if (aSession != null && aSession.isOpen()) {
aSession.close();
}
}
/**
* Counts number of BIObj associated.
*
* @param dsId
* the ds id
* @return Integer, number of BIObj associated
* @throws EMFUserError
* the EMF user error
*/
@Override
public Integer countFederationsUsingDataset(Integer dsId) {
logger.debug("IN");
Integer resultNumber = new Integer(0);
Session session = null;
Transaction transaction = null;
try {
session = getSession();
transaction = session.beginTransaction();
String hql = "select count(*) from SbiDataSetFederation s where s.id.dsId = ? ";
Query aQuery = session.createQuery(hql);
aQuery.setInteger(0, dsId.intValue());
resultNumber = new Integer(((Long) aQuery.uniqueResult()).intValue());
} catch (Throwable t) {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw new SpagoBIDAOException("Error while counting the federations associated with the data set with id " + dsId, t);
} finally {
if (session != null && session.isOpen()) {
session.close();
}
logger.debug("OUT");
}
return resultNumber;
}
@Override
public boolean isTransactionInProgress(
JDBCContext jdbcContext, Context transactionContext, Transaction transaction) {
return (transaction != null && transaction.isActive()) ||
TransactionSynchronizationManager.isActualTransactionActive();
}
@Override
public List<CacheItem> loadAllCacheItems() {
logger.debug("IN");
List<CacheItem> toReturn = new ArrayList<CacheItem>();
Session session = null;
Transaction transaction = null;
try {
session = getSession();
transaction = session.beginTransaction();
Query hibQuery = session.createQuery("from SbiCacheItem");
List hibList = hibQuery.list();
Iterator it = hibList.iterator();
while (it.hasNext()) {
SbiCacheItem hibMap = (SbiCacheItem) it.next();
if (hibMap != null) {
CacheItem cacheItem = toCacheItem(hibMap);
toReturn.add(cacheItem);
}
}
transaction.commit();
} catch (Throwable t) {
if (transaction != null && transaction.isActive()) {
transaction.rollback();
}
throw new SpagoBIDAOException("An unexpected error occured while loading all cache items", t);
} finally {
if (session != null && session.isOpen()) {
session.close();
}
logger.debug("OUT");
}
return toReturn;
}
@GET
@Path("/updates")
public World[] updates(@QueryParam("queries") String queriesParam) throws InterruptedException,
ExecutionException {
final int queries = getQueries(queriesParam);
final World[] worlds = new World[queries];
Callable<World[]> callable = () -> {
Session session = emf.createEntityManager().unwrap(Session.class);
session.setDefaultReadOnly(false);
Transaction txn = session.beginTransaction();
try {
// using write batching. See the data source properties provided
// in the configuration file
// 1. Read and update the entities from the DB
final AtomicInteger ii = new AtomicInteger(0);
ThreadLocalRandom.current().ints(1, 10001).distinct().limit(queries).forEach(
(randomValue)->{
final World world = (World) session.byId(World.class).load(randomValue);
world.setRandomNumber(randomWorld());
worlds[ii.getAndAdd(1)]=world;
}
);
// 2. Sort the array to prevent transaction deadlock in the DB
Arrays.sort(worlds, Comparator.comparingInt(World::getId));
// 3. Actually save the entities
for (int i = 0; i < worlds.length; i++) {
session.persist(worlds[i]);
}
session.flush();
session.clear();
txn.commit();
return worlds;
} catch (RuntimeException e) {
if (txn != null && txn.isActive())
txn.rollback();
throw e;
} finally {
session.close();
}
};
Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable);
return futureWorlds.get();
}
@GET
@Path("/updates")
public World[] updates(@QueryParam("queries") String queriesParam) throws InterruptedException,
ExecutionException {
final int queries = getQueries(queriesParam);
final World[] worlds = new World[queries];
Callable<World[]> callable = () -> {
Session session = emf.createEntityManager().unwrap(Session.class);
session.setDefaultReadOnly(false);
Transaction txn = session.beginTransaction();
try {
// using write batching. See the data source properties provided
// in the configuration file
// 1. Read and update the entities from the DB
for (int i = 0; i < queries; i++) {
final World world = (World) session.byId(World.class).load(randomWorld());
world.setRandomNumber(randomWorld());
worlds[i] = world;
}
// 2. Sort the array to prevent transaction deadlock in the DB
Arrays.sort(worlds, Comparator.comparingInt(World::getId));
// 3. Actually save the entities
for (int i = 0; i < worlds.length; i++) {
session.persist(worlds[i]);
}
session.flush();
session.clear();
txn.commit();
return worlds;
} catch (RuntimeException e) {
if (txn != null && txn.isActive())
txn.rollback();
throw e;
} finally {
session.close();
}
};
Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable);
return futureWorlds.get();
}
/**
* Delete distribution pref
* @param distPrefId
*/
private void doDelete(HttpServletRequest request, String distPrefId) {
Transaction tx = null;
sessionContext.checkPermission(distPrefId, "DistributionPref", Right.ExaminationDistributionPreferenceDelete);
try {
DistributionPrefDAO dpDao = new DistributionPrefDAO();
org.hibernate.Session hibSession = dpDao.getSession();
tx = hibSession.getTransaction();
if (tx==null || !tx.isActive())
tx = hibSession.beginTransaction();
HashSet relatedExams = new HashSet();
DistributionPref dp = dpDao.get(new Long(distPrefId));
PreferenceGroup owner = (PreferenceGroup) dp.getOwner();
owner.getPreferences().remove(dp);
for (Iterator i=dp.getDistributionObjects().iterator();i.hasNext();) {
DistributionObject dObj = (DistributionObject)i.next();
PreferenceGroup pg = dObj.getPrefGroup();
relatedExams.add(pg);
pg.getDistributionObjects().remove(dObj);
hibSession.saveOrUpdate(pg);
}
hibSession.delete(dp);
hibSession.saveOrUpdate(owner);
for (Iterator i=relatedExams.iterator();i.hasNext();) {
Exam exam = (Exam)i.next();
ChangeLog.addChange(
hibSession,
sessionContext,
exam,
ChangeLog.Source.DIST_PREF_EDIT,
ChangeLog.Operation.DELETE,
exam.firstSubjectArea(),
exam.firstDepartment());
}
if (tx!=null && tx.isActive())
tx.commit();
hibSession.flush();
hibSession.refresh(owner);
}
catch (Exception e) {
Debug.error(e);
if (tx!=null && tx.isActive())
tx.rollback();
}
}
/**
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws HibernateException
*/
public ActionForward deleteRoomFeature(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
RoomFeatureEditForm roomFeatureEditForm = (RoomFeatureEditForm) form;
Long id = new Long(roomFeatureEditForm.getId());
RoomFeatureDAO rdao = new RoomFeatureDAO();
org.hibernate.Session hibSession = rdao.getSession();
Transaction tx = null;
try {
tx = hibSession.beginTransaction();
RoomFeature rf = rdao.get(id, hibSession);
if (rf != null) {
sessionContext.checkPermission(rf, rf instanceof GlobalRoomFeature ? Right.GlobalRoomFeatureDelete : Right.DepartmenalRoomFeatureDelete);
ChangeLog.addChange(
hibSession,
sessionContext,
rf,
ChangeLog.Source.ROOM_FEATURE_EDIT,
ChangeLog.Operation.DELETE,
null,
(rf instanceof DepartmentRoomFeature?((DepartmentRoomFeature)rf).getDepartment():null));
for (Iterator i=rf.getRooms().iterator();i.hasNext();) {
Location loc = (Location)i.next();
loc.getFeatures().remove(rf);
hibSession.save(loc);
}
for (RoomFeaturePref p: (List<RoomFeaturePref>)hibSession.createQuery("from RoomFeaturePref p where p.roomFeature.uniqueId = :id")
.setLong("id", id).list()) {
p.getOwner().getPreferences().remove(p);
hibSession.delete(p);
hibSession.saveOrUpdate(p.getOwner());
}
hibSession.delete(rf);
}
tx.commit();
} catch (Exception e) {
if (tx!=null && tx.isActive()) tx.rollback();
throw e;
}
roomFeatureEditForm.setDeptCode((String)sessionContext.getAttribute(SessionAttribute.DepartmentCodeRoom));
return mapping.findForward("showRoomFeatureList");
}
private static void rollbackTransaction(Session session) {
final Transaction txn = session.getTransaction();
if (txn != null && txn.isActive()) {
txn.rollback();
}
}