Java 类org.hibernate.Transaction 实例源码

项目:ImageClassify    文件:ConstantService.java   
@Override
public boolean updateValueOfKey(Constant constant) { 
        Session session = HibernateUtils.getSession();
         Transaction tx = session.beginTransaction();
         boolean isUpdate = false;
         try {
            Query query = session.createQuery("update Constant c set c.value =? where c.id = ?");  
            query.setString(0,constant.getValue());
            query.setInteger(1, constant.getId()); 
            int temp = query.executeUpdate();  
            tx.commit();
            if (temp>0) {
                isUpdate = true;
            }
        } catch (Exception e) {
             e.printStackTrace();
             tx.rollback();
        }finally {
            HibernateUtils.closeSession();
        }   
         return isUpdate;
}
项目:ImageClassify    文件:MarkService.java   
@Override
public boolean updateMarkAll(Mark mark) {
     Session session = HibernateUtils.getSession();
     Transaction tx = session.beginTransaction();
     boolean b = false;
     try {
        Query query = session.createQuery("update Mark m set m.mark_accuracy =?,m.mark_time =?,m.option_mark_name =?,"
                + "m.manual_mark_name=? where m.user_id = ? and m.img_id = ?");  
        query.setString(0, mark.getMark_accuracy());
        query.setTimestamp(1, mark.getMark_time());
        query.setString(2,mark.getOption_mark_name());
        query.setString(3, mark.getManual_mark_name()); 
        query.setInteger(4, mark.getUser_id());
        query.setInteger(5, mark.getImg_id()); 
        query.executeUpdate();  
        tx.commit();
        b = true;
    } catch (Exception e) {
         e.printStackTrace();
         tx.rollback(); 
    }finally {
        HibernateUtils.closeSession();
    } 
     return b;
}
项目:Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update    文件:delete_HQL.java   
public static void main(String[] args) {
    Configuration cfg=null;
    SessionFactory factory=null;
    Session ses=null;
     Transaction tx=null;
            cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
            factory=cfg.buildSessionFactory();
        ses=factory.openSession();

        tx=ses.beginTransaction();
         String hql="delete from bigbazarModel where bazarid=:id";
         Query q=ses.createQuery(hql);
                q.setParameter("id", 1003);
                    int c=q.executeUpdate();
                    //int count=Integer.parseUnsignedInt(c);
                    tx.commit();
                    System.out.println("\t\t"+c+" rows Deleted");

                    factory.close();

}
项目:Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update    文件:copy_HQL.java   
public static void main(String[] args) {
    Configuration cfg=null;
    SessionFactory factory=null;
    Session ses=null;
     Transaction tx=null;
            cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
            factory=cfg.buildSessionFactory();
        ses=factory.openSession();

        tx=ses.beginTransaction();
         String hql="insert into newMall(mallid,item_name,item_price,item_quantity) "
                    + "select bazarid,item_name,item_price,item_quantity from bigbazarModel ";
         Query q=ses.createQuery(hql);
                    int c=q.executeUpdate();
                    //int count=Integer.parseUnsignedInt(c);
                    tx.commit();
                    System.out.println("\t\t"+c+" rows Copied Successfully...");

                    factory.close();

}
项目:Hibernate_HQL_UniqueResult_ExecuteUpdate_CopyData_Delete_Update    文件:update_HQL.java   
public static void main(String[] args) {
    Configuration cfg=null;
    SessionFactory factory=null;
    Session ses=null;
     Transaction tx=null;
            cfg=new Configuration().configure("com/app/cfgs/hibernate.cfg.xml");
            factory=cfg.buildSessionFactory();
        ses=factory.openSession();

        tx=ses.beginTransaction();
         String hql="update bigbazarModel set item_price=:price where bazarid=:id";
         Query q=ses.createQuery(hql);
                q.setParameter("id", 1002);
                q.setParameter("price", 60.0f);
                    int c=q.executeUpdate();
                    //int count=Integer.parseUnsignedInt(c);
                    tx.commit();
                    System.out.println("\t\t"+c+" rows Updated");

                    factory.close();

}
项目:ImageClassify    文件:CategoryService.java   
/**
 * 持久化category对象
 */
@Override
public boolean saveCatogory(Category category) {
    Session session = HibernateUtils.getSession(); // 生成session实例
    Transaction tx = session.beginTransaction(); // 创建transaction实例
    try {
        session.save(category); // 使用session的sava方法将持久化对象保存到数据库中
        tx.commit(); // 提交事务
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback(); // 回滚事务
        return false;
    } finally {
        HibernateUtils.closeSession(); // 关闭Session实例
    }
}
项目:OSWf-OSWorkflow-fork    文件:HibernateStore.java   
protected void save(final Session session, final Object entity) throws HibernateException {

       Transaction transaction = null;

       try {
           transaction = session.beginTransaction();
           session.save(entity);
           transaction.commit();
       } catch (HibernateException hibernateException) {

           if (transaction != null)
               transaction.rollback();

           logger.error(fatal, hibernateException.toString());
           throw hibernateException;
       } 

   }
项目:unitimes    文件:LogCleaner.java   
public static void cleanupOnlineSectioningLog(int days) {
    if (days < 0) return;
    org.hibernate.Session hibSession = new _RootDAO().createNewSession();
    Transaction tx = null;
    try {
        tx = hibSession.beginTransaction();
        int rows = hibSession.createQuery(
                "delete from OnlineSectioningLog where timeStamp < " + HibernateUtil.addDate("current_date()", ":days")
                ).setInteger("days", - days).executeUpdate();
        if (rows > 0)
            sLog.info("All records older than " + days + " days deleted from the online sectioning log (" + rows + " records).");
        tx.commit();
    } catch (Throwable t) {
        sLog.warn("Failed to cleanup query log: " + t.getMessage(), t);
        if (tx != null) tx.rollback();
    } finally {
        hibSession.close();
    }
}
项目:ImageClassify    文件:ImageService.java   
@Override
public boolean saveImageCategory(Image_Category image_Category) {
    Session session = HibernateUtils.getSession(); //生成session实例
    Transaction tx = session.beginTransaction();  //创建transaction实例

    try {   
        session.save(image_Category); 
        tx.commit();            //提交事务 
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();          //回滚事务 
        return false;
    }finally {
      HibernateUtils.closeSession();  //关闭Session实例
    } 
}
项目:FlashBoard    文件:Driver2.java   
public static void testUserCreation() {
    Session session = HibernateUtil.getSession();
    Transaction tx = null;

    User newUser = new User("jef", "jeff", "jeff", "jeff", "jeff");
    //SQLIntegrityConstraintViolationException
    try {
        tx = session.beginTransaction();
        session.save(newUser);
        tx.commit();
        System.out.println("User: '" + newUser.getUsername() + "' has been successfully created!");
    } catch (HibernateException he) {
        if (tx != null) {
            tx.rollback();
        }
        System.out.println("User creation failed!");
        he.printStackTrace();

    } finally {
        session.close();
    }
}
项目:unitimes    文件:UniTimeClusterDiscovery.java   
protected void remove(Address addr) {
    if (!ClusterDiscoveryDAO.isConfigured()) return;
    org.hibernate.Session hibSession = ClusterDiscoveryDAO.getInstance().createNewSession();
String own_address = addressAsString(addr);
Transaction tx = null;
      try {
        tx = hibSession.beginTransaction();
        ClusterDiscovery cluster = ClusterDiscoveryDAO.getInstance().get(new ClusterDiscovery(own_address, cluster_name), hibSession);
        if (cluster != null)
            hibSession.delete(cluster);
        hibSession.flush();
          if (tx != null) tx.commit();
      } catch (Exception e) {
    if (tx != null) tx.rollback();
    log.info("Failed to delete data for cluster " + cluster_name + ": " + e.getMessage());
} finally {
    hibSession.close();
}
  }
项目:FlashBoard    文件:QuizDaoImpl.java   
public Integer insertQuiz(Quiz quiz) {
    Session session = HibernateUtil.getSession();
    Transaction tx = null;
    Integer quizId = null;

    try {
        // Attemps to add and get quiz Id back
        tx = session.beginTransaction();
        quizId = (Integer) session.save(quiz);
        System.out.println(quizId);
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            // Roll back IF transaction fails
            tx.rollback();
        }
        e.printStackTrace();
    } finally {
        session.close();
    }

    return quizId;
}
项目:FlashBoard    文件:AdminDaoImpl.java   
@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;
}
项目:FlashBoard    文件:AdminDaoImpl.java   
@Override
public boolean promoteUserToWriter(String username) {
    Boolean bool = false;
    Session session = HibernateUtil.getSession();
    Transaction tx = null;
    User myUser = udi.getUserByUsername(username);
    try {
        tx = session.beginTransaction();
        myUser.setRoleFlag(2);
        session.save(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;
}
项目:FlashBoard    文件:AdminDaoImpl.java   
@Override
public boolean deleteUserAccount(String username) {
    Boolean bool = false;
    Session session = HibernateUtil.getSession();
    Transaction tx = null;
    User myUser = udi.getUserByUsername(username);
    try {
        tx = session.beginTransaction();
        myUser.setBlacklisted(true);
        session.delete(myUser);
        tx.commit();
        bool = true;
        System.out.println("User: '" + username + "' successfully deleted.");
    } catch (HibernateException he) {
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        session.close();
    }
    return bool;
}
项目:Learning-Spring-5.0    文件:BookDAO_SessionFactory.java   
@Override
public int addBook(Book book) {
    // TODO Auto-generated method stub

    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    try {
        session.saveOrUpdate(book);
        transaction.commit();
        session.close();
        return 1;
    } catch (DataAccessException exception) {
        exception.printStackTrace();
    }
    return 0;

}
项目:unitimes    文件:LogCleaner.java   
public static void cleanupQueryLog(int days) {
    if (days < 0) return;
    org.hibernate.Session hibSession = new _RootDAO().createNewSession();
    Transaction tx = null;
    try {
        tx = hibSession.beginTransaction();
        int rows = hibSession.createQuery(
                "delete from QueryLog where timeStamp < " + HibernateUtil.addDate("current_date()", ":days")
                ).setInteger("days", - days).executeUpdate();
        if (rows > 0)
            sLog.info("All records older than " + days + " days deleted from the query log (" + rows + " records).");
        tx.commit();
    } catch (Throwable t) {
        sLog.warn("Failed to cleanup query log: " + t.getMessage(), t);
        if (tx != null) tx.rollback();
    } finally {
        hibSession.close();
    }
}
项目:unitimes    文件:InstructorSchedulingDatabaseLoader.java   
public void load() throws Exception {
    ApplicationProperties.setSessionId(iSessionId);
    org.hibernate.Session hibSession = null;
    Transaction tx = null;
    try {
        hibSession = TimetableManagerDAO.getInstance().createNewSession();
        hibSession.setCacheMode(CacheMode.IGNORE);
        hibSession.setFlushMode(FlushMode.COMMIT);

        tx = hibSession.beginTransaction(); 

        load(hibSession);

        tx.commit();
    } catch (Exception e) {
        iProgress.fatal("Unable to load input data, reason: " + e.getMessage(), e);
        tx.rollback();
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession != null && hibSession.isOpen()) hibSession.close();
    }
}
项目:ImageClassify    文件:ConstantService.java   
@Override
public List<Constant> getConstantByKey() {

     Session session = HibernateUtils.getSession();
     Transaction tx = session.beginTransaction(); 
     List<Constant> constants = new ArrayList<Constant>();
     try {
         constants.add((Constant) session.createCriteria(Constant.class).add(Restrictions.eq("key", cn.codekong.config.Constant.IDENTITY_TIME)).uniqueResult());
         constants.add((Constant) session.createCriteria(Constant.class).add(Restrictions.eq("key", cn.codekong.config.Constant.IDENTIFY_FREQUENCY_MARKS)).uniqueResult());
         tx.commit();
     } catch (Exception e) {
         e.printStackTrace();
         tx.rollback();
    }finally {
        HibernateUtils.closeSession();
    }   
     return constants;
}
项目:ImageClassify    文件:UserService.java   
/**
 * @param id
 * 根据用户的标识id找到该用户并返回
 */
@Override
public User findUserById(int user_id) {
     User user = null;
     Session session = HibernateUtils.getSession();//生成Session实例
     Transaction tx = session.beginTransaction();//生成事务实例
     try {
         user =  (User) session.get(User.class, user_id);
         //调用session的get()方法,找到此用户到内存中
        tx.commit();//提交事务
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();//事务回滚
    }finally{
        HibernateUtils.closeSession();//关闭session实例
    }
     return user;
}
项目:ImageClassify    文件:ImageService.java   
@Override
public List<Image> getFinishedImages() {
    List<Image> images = new ArrayList<Image>();
       Session session = HibernateUtils.getSession();//生成Session实例
    Transaction tx = session.beginTransaction();//生成事务实例 

     try {
         images = session.createQuery("select new Image(img_id,img_label_name) from Image where img_is_finish = 1").list();
         tx.commit();//提交事务
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();
    }finally {
        HibernateUtils.closeSession();//关闭session实例
    }
     return images; 
}
项目:ImageClassify    文件:OauthService.java   
@Override
 /**
  * 更新token对象
  * @param oauth
  * @return
  */
public boolean updateOauth(Oauth oauth) {
     Session session = HibernateUtils.getSession();
     Transaction tx = session.beginTransaction();

     try { 
        session.update(oauth); //调用session的update方法更新oauth对象
        tx.commit(); 
        return true;
    } catch (Exception e) {
         e.printStackTrace();
         tx.rollback(); 
         return false;
    }finally {
        HibernateUtils.closeSession();
    }  
}
项目:ImageClassify    文件:TaskService.java   
/**
 * 获取user_id对应的已提交的Task
 */
@Override
public List<Task> geTasksOfUnconfirmed(int user_id,int start,int num) {
    List<Task> tasks = new ArrayList<Task>();  
    Session session = HibernateUtils.getSession();//生成Session实例
     Transaction tx = session.beginTransaction();//生成事务实例
     try {

         Query query =  session.createQuery("SELECT  new Task( task_id,task_img_amount,task_start_time,user_id) FROM Task WHERE task_iscommit = 1 AND user_id = "+user_id);
         query.setFirstResult(start-1);
         query.setMaxResults(num);
         tasks = query.list(); 
         tx.commit();//提交事务
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();//事务回滚
    }finally{
        HibernateUtils.closeSession();//关闭session实例
    }
     return tasks; 
}
项目:unitimes    文件:TimetableDatabaseLoader.java   
public void load() {
    ApplicationProperties.setSessionId(iSessionId);
    org.hibernate.Session hibSession = null;
    Transaction tx = null;
    try {
        hibSession = TimetableManagerDAO.getInstance().getSession();
        hibSession.setCacheMode(CacheMode.IGNORE);
        hibSession.setFlushMode(FlushMode.COMMIT);

        tx = hibSession.beginTransaction(); 

        load(hibSession);

        tx.commit();
    } catch (Exception e) {
        iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load input data, reason:"+e.getMessage(),e);
        tx.rollback();
    } finally {
        // here we need to close the session since this code may run in a separate thread
        if (hibSession!=null && hibSession.isOpen()) hibSession.close();
    }
}
项目:Learning-Spring-5.0    文件:BookDAO_SessionFactory.java   
@Override
public int updateBook(long ISBN, int price) {
    // TODO Auto-generated method stub

    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    try {
        Book book = session.get(Book.class, ISBN);
        book.setPrice(price);

        session.saveOrUpdate(book);
        transaction.commit();
        session.close();
        return 1;
    } catch (DataAccessException exception) {
        exception.printStackTrace();
    }
    return 0;

}
项目:ImageClassify    文件:OauthService.java   
/**
 * 依据oauth_token找到oauth实体对象
 */
@Override
public Oauth findOauthByOauthToken(String oauth_token) {
     Oauth oauth = null;
     Session session = HibernateUtils.getSession();
     Transaction tx = session.beginTransaction(); //开启事务
     try {
         //使用criteria查询oauth对象
          oauth = (Oauth) session.createCriteria(Oauth.class).add(Restrictions.eq("oauth_token", oauth_token)).uniqueResult();
          tx.commit();
    } catch (Exception e) {
      e.printStackTrace();
      tx.rollback();
    }finally{
        HibernateUtils.closeSession();
    }
     return oauth; //返回oauth对象
}
项目:ImageClassify    文件:TaskService.java   
@Override
public String getAmountTaskOfCommit(int user_id) {
    String sql = "SELECT COUNT(*) FROM task WHERE task_iscommit=1 AND user_id =" + user_id;
    Session session = HibernateUtils.getSession();
    Transaction tx = session.beginTransaction(); //开启事务
    int num = 0;
    try {
        num = Integer.parseInt(session.createSQLQuery(sql).list().get(0).toString());
        tx.commit();//提交事务 
    } catch (Exception e) {
      e.printStackTrace();
      tx.rollback();
    }finally{
        HibernateUtils.closeSession();
    } 
    return num+"";
}
项目:unitimes    文件:RoomSharingBackend.java   
public RoomSharingModel saveEventAvailability(RoomSharingRequest request, SessionContext context) {
    context.checkPermission(request.getLocationId(), "Location", Right.RoomEditEventAvailability);

    String availability = "";
    for (int d = 0; d < 7; d++)
        for (int s = 0; s < 288; s ++) {
            RoomSharingOption option = request.getModel().getOption(d, s);
            availability += (option.getId() == -1l ? '0' : '1');
        }

    org.hibernate.Session hibSession = LocationDAO.getInstance().getSession();
    Transaction tx = hibSession.beginTransaction();
    try {

        Location location = LocationDAO.getInstance().get(request.getLocationId(), hibSession);
        location.setEventAvailability(availability);
        hibSession.save(location);

        ChangeLog.addChange(hibSession, context, location, ChangeLog.Source.ROOM_DEPT_EDIT, ChangeLog.Operation.UPDATE, null, location.getControllingDepartment());

        tx.commit();

        return null;

    } catch (Exception ex) {
        tx.rollback();
        if (ex instanceof GwtRpcException) throw (GwtRpcException)ex;
        throw new GwtRpcException(ex.getMessage(), ex);
    }
}
项目:ctsms    文件:OpsSystDaoImpl.java   
@Override
public void handleRemoveTxn(Long opsSystId) throws Exception {
    Transaction transaction = this.getSession(true).beginTransaction();
    try {
        removeOpsSyst(opsSystId);
        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    }
}
项目:hibernate-ogm-redis    文件:MapMappingTest.java   
@Test
public void testMapOfComponent() {
    OgmSession session = openSession();
    Transaction tx = session.beginTransaction();

    Map<String, Department> departments = new HashMap<>();
    departments.put( "sawing", new Department( "Sawing", 7 ) );
    departments.put( "sale", new Department( "Sale", 2 ) );
    Enterprise timberTradingInc = new Enterprise( "enterprise-1", departments );

    session.persist( timberTradingInc );
    tx.commit();
    session.clear();

    tx = session.beginTransaction();

    // assert
    assertDbObject(
            session.getSessionFactory(),
            // collection
            "Enterprise",
            // query
            "enterprise-1",
            // expected
            "{ " +
                "'departments' : {" +
                    "'sawing' : { 'name' : 'Sawing', 'headCount'  : 7 }," +
                    "'sale' : { 'name' : 'Sale', 'headCount'  : 2 }," +
                "}" +
            "}"
    );

    // clean up
    session.delete( timberTradingInc );

    tx.commit();
    session.close();
    checkCleanCache();
}
项目:ImageClassify    文件:CompositionService.java   
/**
 * 获取指定task_id对应的任务所有图片
 */
@Override
public List<Image> getTaskOfImages(int task_id) {

     List<Image> images = new ArrayList<Image>();
     Session session = HibernateUtils.getSession();//生成Session实例
     Transaction tx = session.beginTransaction();//生成事务实例 
     try { 
        Query query = session.createSQLQuery("SELECT  image.img_id,img_name,img_path FROM composition,image WHERE composition.img_id = image.img_id AND composition.task_id = "+task_id).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); 
            query.setFirstResult(0);
            query.setMaxResults(5);
        images = query.list();
         //调用session的get()方法,找到此用户到内存中
        tx.commit();//提交事务
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();//事务回滚
    }finally{
        HibernateUtils.closeSession();//关闭session实例
    }    
     List<Image> images2 = new ArrayList<Image>(); 

     for (int i = 0; i < images.size(); i++) { 
          Image image = new Image();
          Map map = (Map) images.get(i); 
          image.setImg_id(Integer.parseInt(map.get("img_id")+"")); 
          image.setImg_name(map.get("img_name")+"");
          image.setImg_path(map.get("img_path")+"");
          images2.add(image);
     }  
     return images2;
}
项目:otus_java_2017_04    文件:DBServiceImpl.java   
private <R> R runInSession(Function<Session, R> function) {
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = session.beginTransaction();
        R result = function.apply(session);
        transaction.commit();
        return result;
    }
}
项目:LibrarySystem    文件:TestAdmin.java   
@Test
public void testSaveAdmin3(){
    SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    Authorization authorization = new Authorization();

    authorization.setAid(2);
    session.save(authorization);

    transaction.commit();
    session.close();
}
项目:ImageClassify    文件:MarkService.java   
@Override
public List<Image_Mark> getImageMark(int img_id) {
    List<Image_Mark> image_Marks = new ArrayList<Image_Mark>();
    Session session = HibernateUtils.getSession(); //生成session实例
    Transaction tx = session.beginTransaction();  //创建transaction实例
    try {  

        Query query = session.createSQLQuery("SELECT option_mark_name,manual_mark_name FROM image_mark where img_id = "+img_id)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP) ; 
        image_Marks = query.list();
        tx.commit();            //提交事务 
    } catch (Exception e) {
        e.printStackTrace();
        tx.rollback();          //回滚事务 
    }finally {
      HibernateUtils.closeSession();  //关闭Session实例
    }

     List<Image_Mark> marks = new ArrayList<Image_Mark>();
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

     for (int i = 0; i < image_Marks.size(); i++) { 
         Image_Mark image_Mark = new Image_Mark();
          Map map = (Map) image_Marks.get(i);
          //img_machine_tag_label,img_path,img_name,user_id,img_id 
          image_Mark.setManual_mark_name(map.get("manual_mark_name")+"");
          image_Mark.setOption_mark_name(map.get("option_mark_name")+"");
          marks.add(image_Mark);
     }  
     return marks; 
}
项目:otus_java_2017_06    文件:DBServiceImpl.java   
private <R> R runInSession(Function<Session, R> function) {
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = session.beginTransaction();
        R result = function.apply(session);
        transaction.commit();
        return result;
    }
}
项目:OSWf-OSWorkflow-fork    文件:HibernatePersistentVarsDAO.java   
public HibernatePersistentVarsItem findByKey(Long piid, String key) {

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

        if( key == null)
            throw new PersistentVarsException("Could not find property for 'null' key");

        Session session = null;
        Transaction transaction = null;
        HibernatePersistentVarsItem item = null;

        try {

            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            item = getItem(session, piid, key);
            session.flush();

            transaction.commit();

        } catch (HibernateException hibernateException) {
            throw new PersistentVarsException("Could not find key '" + key + "': " + hibernateException.getMessage());
        } finally {
            if (transaction != null && transaction.isActive())
                 transaction.rollback();

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

        return item;
    }
项目:unitimes    文件:Exam.java   
public String unassign(String managerExternalId, Session hibSession) {
    Transaction tx = null;
    try {
        if (hibSession.getTransaction()==null || !hibSession.getTransaction().isActive())
            tx = hibSession.beginTransaction();

        ExamAssignment oldAssignment = new ExamAssignment(this);

        setAssignedPeriod(null);
        if (getAssignedRooms()==null) setAssignedRooms(new HashSet());
        getAssignedRooms().clear();
        setAssignedPreference(null);

        HashSet otherExams = new HashSet();

        for (Iterator j=getConflicts().iterator();j.hasNext();) {
            ExamConflict conf = (ExamConflict)j.next();
            for (Iterator i=conf.getExams().iterator();i.hasNext();) {
                Exam x = (Exam)i.next();
                if (!x.equals(this)) {
                    x.getConflicts().remove(conf);
                    otherExams.add(x);
                }
            }
            hibSession.delete(conf);
            j.remove();
        }

        ExamEvent event = getEvent();
        if (event!=null) hibSession.delete(event);

        hibSession.update(this);
        for (Iterator i=otherExams.iterator();i.hasNext();)
            hibSession.update((Exam)i.next());

        SubjectArea subject = null;
        Department dept = null;
        for (Iterator i=new TreeSet(getOwners()).iterator();i.hasNext();) {
            ExamOwner owner = (ExamOwner)i.next();
            subject = owner.getCourse().getSubjectArea();
            dept = subject.getDepartment();
            break;
        }

        ChangeLog.addChange(hibSession,
                TimetableManager.findByExternalId(managerExternalId),
                getSession(),
                this,
                getName()+" ("+
                (oldAssignment.getPeriod()==null?"N/A":oldAssignment.getPeriodAbbreviation()+" "+oldAssignment.getRoomsName(", "))+
                " &rarr; N/A)",
                ChangeLog.Source.EXAM_INFO,
                ChangeLog.Operation.UNASSIGN,
                subject,
                dept);

        if (tx!=null) tx.commit();
        return null;
    } catch (Exception e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
        return "Unassignment of "+getName()+" failed, reason: "+e.getMessage();
    }
}
项目:OSWf-OSWorkflow-fork    文件:HibernateStore.java   
public List<Step> findCurrentSteps(final long entryId) throws WorkflowStoreException {

        Session session = null;
        Transaction transaction = null;
        List<Step> steps = null;

        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            steps = loadEntry(session, entryId).getCurrentSteps();

            transaction.commit();

         } catch (HibernateException hibernateException) {
            throw new WorkflowStoreException(hibernateException);
        } finally {

            if (transaction != null && transaction.isActive())
                 transaction.rollback();

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

        return steps;
    }
项目:OSWf-OSWorkflow-fork    文件:HibernateStore.java   
public ProcessInstance findProcessInstance(long entryId) throws WorkflowStoreException {

       Session session = null;
       Transaction transaction = null;
       ProcessInstance workflowEntry = null;

       try {
           session = sessionFactory.openSession();
           transaction = session.beginTransaction();

           workflowEntry = loadEntry(session, entryId);

           transaction.commit();

       } catch (HibernateException hibernateException) {
           throw new WorkflowStoreException(hibernateException);
       } finally {

           if (transaction != null && transaction.isActive())
                transaction.rollback();

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

       return workflowEntry;
   }
项目:OSWf-OSWorkflow-fork    文件:HibernateStore.java   
public List<Step> findHistorySteps(final long entryId) throws WorkflowStoreException {

        Session session = null;
        Transaction transaction = null;
        List<Step> steps = null;

        try {
            session = sessionFactory.openSession();
            transaction = session.beginTransaction();

            steps = loadEntry(session, entryId).getHistorySteps();

            transaction.commit();

         } catch (HibernateException hibernateException) {
            throw new WorkflowStoreException(hibernateException);
        } finally {

            if (transaction != null && transaction.isActive())
                 transaction.rollback();

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

        return steps;
    }