Package net.sf.hibernate

Examples of net.sf.hibernate.Session


   * @throws DataAccessResourceFailureException if the Session could not be created
   * @see org.springframework.orm.hibernate.SessionFactoryUtils#getSession(SessionFactory, boolean)
   * @see net.sf.hibernate.FlushMode#NEVER
   */
  protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    session.setFlushMode(FlushMode.NEVER);
    return session;
  }
View Full Code Here


    Assert.notNull(sessionFactory, "No SessionFactory specified");

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && !sessionHolder.isEmpty()) {
      // pre-bound Hibernate Session
      Session session = null;
      if (TransactionSynchronizationManager.isSynchronizationActive() &&
          sessionHolder.doesNotHoldNonDefaultSession()) {
        // Spring transaction management is active ->
        // register pre-bound Session with it for transactional flushing.
        session = sessionHolder.getValidatedSession();
        if (!sessionHolder.isSynchronizedWithTransaction()) {
          logger.debug("Registering Spring transaction synchronization for existing Hibernate Session");
          TransactionSynchronizationManager.registerSynchronization(
              new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false));
          sessionHolder.setSynchronizedWithTransaction(true);
          // Switch to FlushMode.AUTO if we're not within a read-only transaction.
          FlushMode flushMode = session.getFlushMode();
          if (FlushMode.NEVER.equals(flushMode) &&
              !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
            session.setFlushMode(FlushMode.AUTO);
            sessionHolder.setPreviousFlushMode(flushMode);
          }
        }
      }
      else {
        // No Spring transaction management active -> try JTA transaction synchronization.
        session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator);
      }
      if (session != null) {
        return session;
      }
    }

    try {
      logger.debug("Opening Hibernate Session");
      Session session = (entityInterceptor != null ?
          sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession());

      // Set Session to FlushMode.NEVER if we're within a read-only transaction.
      // Use same Session for further Hibernate actions within the transaction.
      // Thread object will get removed by synchronization at transaction completion.
      if (TransactionSynchronizationManager.isSynchronizationActive()) {
        // We're within a Spring-managed transaction, possibly from JtaTransactionManager.
        logger.debug("Registering Spring transaction synchronization for new Hibernate Session");
        SessionHolder holderToUse = sessionHolder;
        if (holderToUse == null) {
          holderToUse = new SessionHolder(session);
        }
        else {
          holderToUse.addSession(session);
        }
        if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
          session.setFlushMode(FlushMode.NEVER);
        }
        TransactionSynchronizationManager.registerSynchronization(
            new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true));
        holderToUse.setSynchronizedWithTransaction(true);
        if (holderToUse != sessionHolder) {
View Full Code Here

        // Look for transaction-specific Session.
        Transaction jtaTx = jtaTm.getTransaction();
        if (jtaTx != null) {
          int jtaStatus = jtaTx.getStatus();
          if (jtaStatus == Status.STATUS_ACTIVE || jtaStatus == Status.STATUS_MARKED_ROLLBACK) {
            Session session = sessionHolder.getValidatedSession(jtaTx);
            if (session == null && !sessionHolder.isSynchronizedWithTransaction()) {
              // No transaction-specific Session found: If not already marked as
              // synchronized with transaction, register the default thread-bound
              // Session as JTA-transactional. If there is no default Session,
              // we're a new inner JTA transaction with an outer one being suspended:
              // In that case, we'll return null to trigger opening of a new Session.
              session = sessionHolder.getValidatedSession();
              if (session != null) {
                logger.debug("Registering JTA transaction synchronization for existing Hibernate Session");
                sessionHolder.addSession(jtaTx, session);
                jtaTx.registerSynchronization(
                    new SpringJtaSynchronizationAdapter(
                        new SpringSessionSynchronization(sessionHolder, sessionFactory, jdbcExceptionTranslator, false),
                        jtaTm));
                sessionHolder.setSynchronizedWithTransaction(true);
                // Switch to FlushMode.AUTO if we're not within a read-only transaction.
                FlushMode flushMode = session.getFlushMode();
                if (FlushMode.NEVER.equals(flushMode)) {
                  session.setFlushMode(FlushMode.AUTO);
                  sessionHolder.setPreviousFlushMode(flushMode);
                }
              }
            }
            return session;
View Full Code Here

    }
    else {
      if (isSingleSession()) {
        // single session mode
        logger.debug("Opening single Hibernate Session in OpenSessionInViewInterceptor");
        Session session = SessionFactoryUtils.getSession(
            getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
        applyFlushMode(session, false);
        TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
      }
      else {
View Full Code Here

        // cast to the types I want to use
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession(true);

        Session ses = null;
        boolean sessionCreated = false;

        try
        {
            chain.doFilter(request, response);
View Full Code Here

    //~ Methods ================================================================

    public static Session currentSession() throws PersistenceException
    {
        Session s = (Session) session.get();

        if (s == null)
        {
            s = PersistenceManager.openSession();
            if (log.isDebugEnabled())
View Full Code Here

        return s;
    }

    public static void closeSession() throws HibernateException, JDBCException
    {
        Session s = (Session) session.get();
        session.set(null);

        if (s != null)
        {
            if (s.isOpen())
            {
                s.flush();
                s.close();

                if (log.isDebugEnabled())
                {
                    log.debug("Closed hibernate session.");
                }
View Full Code Here

import java.util.List;

// Repository for files and directories
public class FileSystemImpl implements FileSystem {
    public Directory getRootDirectory() throws HibernateException {
        Session session = ThreadSession.get();
        List dirs = session.createQuery(
                "from dir in " + Directory.class + " where dir.parent is null").
                setMaxResults(1).list();
        if (dirs.iterator().hasNext()) {
            return (Directory)dirs.iterator().next();
        } else {
            Directory root = new Directory();
            root.setName("");
            session.save(root);
            session.flush();
            session.refresh(root);
            return root;
        }
    }
View Full Code Here

    }

    public Directory getDirectory(String path) throws HibernateException {
        String[] pathElements = path.split("/");
        Directory dir = getRootDirectory();
        Session session = ThreadSession.get();
        for (int i = 1; i < pathElements.length; i++) {
            List subdirectory = session.createQuery(
                    "from dir in "+Directory.class+" where dir.parent = :parent and dir.name = :name").
                    setParameter("parent", dir, Hibernate.entity(Directory.class)).
                    setParameter("name", pathElements[i]).
                    setMaxResults(1).list();
            if (subdirectory.size() > 0) {
View Full Code Here

                "select person.name, person.id from person in "
                + "class org.nxplanner.domain.Person where person.hidden = 0";

        HashMap names = new HashMap();
        try {
            Session session = GlobalSessionFactory.get().openSession();
            try {
                names.clear();
                List nameResults = session.find(namesQuery);
                Iterator iter = nameResults.iterator();
                while (iter.hasNext()) {
                    Object[] result = (Object[])iter.next();
                    names.put(result[1], result[0]);
                }

                developerMetrics.clear();
                List acceptedTasks =
                        session.find(acceptedTaskQuery, new Integer(userStoryId), Hibernate.INTEGER);
                Iterator acceptedTaskIter = acceptedTasks.iterator();
                while (acceptedTaskIter.hasNext()) {
                    Object[] result = (Object[])acceptedTaskIter.next();
                    double acceptedHours = toDouble(result[2]);
                    if (acceptedHours > 0.0) {
                        getDeveloperMetrics(
                                (String)names.get(result[1]),
                                toInt(result[1]),
                                userStoryId).setAcceptedHours(
                                        acceptedHours);
                    }
                }

                totalHours = 0.0;
                maxDeveloperHours = 0.0;
                List hoursResults = session.find(hoursQuery, new Integer(userStoryId), Hibernate.INTEGER);
                Iterator hoursIterator = hoursResults.iterator();
                while (hoursIterator.hasNext()) {
                    Object[] result = (Object[])hoursIterator.next();
                    int person1Id = toInt(result[0]);
                    int person2Id = toInt(result[1]);
                    Date startTime = (Date)result[2];
                    Date endTime = (Date)result[3];
                    double duration = toDouble(result[5]);
                    if ((endTime != null && startTime != null) || duration != 0) {
                        double hours =
                                duration == 0 ? (endTime.getTime() - startTime.getTime()) / 3600000.0 : duration;
                        boolean isPaired = person1Id != 0 && person2Id != 0;
                        if (person1Id != 0) {
                            updateWorkedHours(
                                    userStoryId,
                                    (String)names.get(result[0]),
                                    person1Id,
                                    hours,
                                    isPaired
                            );
                            totalHours += hours;
                        }
                        if (person2Id != 0) {
                            updateWorkedHours(
                                    userStoryId,
                                    (String)names.get(result[1]),
                                    person2Id,
                                    hours,
                                    isPaired
                            );
                            totalHours += hours;
                        }
                    }
                }
            } catch (Exception ex) {
                if (session.isConnected()) {
                    session.connection().rollback();
                }
                log.error("error", ex);
            } finally {
                session.close();
            }
        } catch (Exception ex) {
            log.error("error", ex);
        }
    }
View Full Code Here

TOP

Related Classes of net.sf.hibernate.Session

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.