コード例 #1
1
ファイル: Topic.java プロジェクト: LennartC/CQ2-Sim
  public static Topic createFromDB(int topicID) {
    Topic topic = null;
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select t, count(p.postID) "
                  + "  from Topic as t, Post as p "
                  + " where t.topicID = p.topicID "
                  + "   and t.topicID = :topicid "
                  + " group by t.topicID");
      q.setInteger("topicid", topicID);

      for (Iterator<Object[]> it = q.iterate(); it.hasNext(); ) {
        Object[] el = it.next();
        topic = (Topic) el[0];
        Long replies = (Long) el[1];
        topic.setReplies(replies == null ? 0 : replies.intValue());
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return topic;
  }
コード例 #2
0
 @SuppressWarnings("unchecked")
 public List<MessageBundleProperty> getModifiedProperties(
     int sortOrder, int sortField, int startingIndex, int pageSize) {
   String orderBy = "asc";
   if (sortOrder == SORT_ORDER_DESCENDING) {
     orderBy = "desc";
   }
   String sortFieldName = "id";
   if (sortField == SORT_FIELD_MODULE) {
     sortFieldName = "moduleName";
   }
   if (sortField == SORT_FIELD_PROPERTY) {
     sortFieldName = "propertyName";
   }
   if (sortField == SORT_FIELD_LOCALE) {
     sortFieldName = "locale";
   }
   if (sortField == SORT_FIELD_BASENAME) {
     sortFieldName = "baseName";
   }
   org.hibernate.Query query = null;
   String queryString =
       "from MessageBundleProperty where value != null order by " + sortFieldName + " " + orderBy;
   try {
     query = getSession().createQuery(queryString);
     query.setFirstResult(startingIndex);
     query.setMaxResults(pageSize);
     return query.list();
   } catch (HibernateException e) {
     throw new RuntimeException(e.getMessage(), e);
   }
 }
コード例 #3
0
ファイル: RateCodesDAO.java プロジェクト: muraleekrish/pric
 public HashMap getAllRateCodes() {
   /**
    * Requires - Modifies - Effects -
    *
    * @throws -
    */
   Criteria objCriteria = null;
   Session objSession = null;
   Integer totRecordCount = null;
   List objList = null;
   HashMap hmResult = new HashMap();
   try {
     logger.info("GETTING ALL RATE CODES");
     objSession = HibernateUtil.getSession();
     objCriteria = objSession.createCriteria(RateCodesVO.class);
     totRecordCount = new Integer(objCriteria.list().size());
     objList = objCriteria.list();
     hmResult.put("TotalRecordCount", totRecordCount);
     hmResult.put("Records", objList);
     logger.info("GOT ALL RATE CODES");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL RATE CODES", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return hmResult;
 }
コード例 #4
0
  public ArrayList<StaffEntity> getAllStaff() {

    Session session = SessionFactoryProvider.getSessionFactory().openSession();

    ArrayList<StaffEntity> departmentStaff = new ArrayList<StaffEntity>();
    Transaction dbTransaction = null;

    try {
      dbTransaction = session.beginTransaction();
      List staffInDB = session.createQuery("FROM StaffEntity ").list();

      for (Iterator iterator = staffInDB.iterator(); iterator.hasNext(); ) {

        StaffEntity staff = (StaffEntity) iterator.next();
        departmentStaff.add(staff);
      }

      dbTransaction.commit();

    } catch (HibernateException error) {
      if (dbTransaction != null) dbTransaction.rollback();
      error.printStackTrace();
    } finally {
      session.close();
    }

    log.info("Number of staff on the department: " + departmentStaff.size());

    return departmentStaff;
  }
コード例 #5
0
ファイル: DbHelper.java プロジェクト: Yogitha6/Campus-Talk
 public List<User> getUserSearchResults(int topicId) {
   // TODO Auto-generated method stub
   List<User> userArr = new ArrayList<User>();
   Session session = sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query1 = session.createQuery("select userId from UserTopic where topicId = :topicId");
     query1.setString("topicId", String.valueOf(topicId));
     Query query2 = session.createQuery("from User where userId in (:userList)");
     query2.setParameterList("userList", query1.list());
     userArr = query2.list();
     /*for(Topic topic : topicArr){
     	System.out.println("Topic Description----"+topic.getTopicDescription());
     	System.out.println("Topic Id----"+topic.getTopicId());
     }*/
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
   return userArr;
 }
コード例 #6
0
ファイル: DbHelper.java プロジェクト: Yogitha6/Campus-Talk
  @Override
  public void saveEventDetails(Event event) {
    // TODO Auto-generated method stub

    // Opening a session to create a database connection
    Session session = this.sessionFactory.openSession();

    // for CRUD operations, we need to create a transaction
    Transaction tx = null;

    // adding a try catch block for maintaining the atomicity of transaction
    try {
      tx = session.beginTransaction();
      System.out.println("DbHelper..saveEventDetails");

      // session save inserts the object into DB
      session.save(event);

      tx.commit();
      System.out.println("Event saved");
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
  }
コード例 #7
0
ファイル: DbHelper.java プロジェクト: Yogitha6/Campus-Talk
 @Override
 public void deleteSubscription(int userId, int forumId) {
   // TODO Auto-generated method stub
   Session session = this.sessionFactory.openSession();
   Transaction tx = null;
   try {
     tx = session.beginTransaction();
     Query query =
         session.createQuery(
             "delete from Subscription where userId = :userId and forumId = :forumId");
     query.setParameter("userId", userId);
     query.setParameter("forumId", forumId);
     int result = query.executeUpdate();
     System.out.println("Execute query..");
     if (result > 0) {
       tx.commit();
       // System.out.println("Subscription Removed..");
     } else {
       // System.out.println("Subscription does not exist");
       tx.rollback();
     }
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
 }
コード例 #8
0
  @Override
  public List<Role> getAllRoles() {

    Session session = SessionFactoryProvider.getSessionFactory().openSession();
    Transaction tx = null;
    List<Role> allRoles = new ArrayList<Role>();

    try {
      tx = session.beginTransaction();
      Criteria criteria = session.createCriteria(Role.class);
      List<Role> roles = criteria.list();

      for (Role r : roles) {
        allRoles.add(r);
      }

      tx.commit();
    } catch (HibernateException e) {
      if (tx != null) {
        e.printStackTrace();
      }
    } finally {
      session.close();
    }

    return allRoles;
  }
コード例 #9
0
ファイル: Topic.java プロジェクト: LennartC/CQ2-Sim
  public static HashMap<Integer, Integer> getUnseenTopics(User user) {

    HashMap<Integer, Integer> unseenHash = new HashMap<Integer, Integer>();
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select location, count(*) from Topic as t"
                  + " where t.topicID not in ("
                  + "		select topicID from LastseenTopic as l where l.userID = :userid and l.lasttime >= t.lastedit"
                  + "       )"
                  + " group by location");
      q.setInteger("userid", user.getId());

      List<Object[]> lsts = q.list();
      for (Object[] o : lsts) {
        unseenHash.put(new Integer("" + o[0]), new Integer("" + o[1]));
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return unseenHash;
  }
コード例 #10
0
  public static double getRate(int GivenCreditScore) {
    // FinalExam - please implement
    // Figure out which row makes sense- return back the
    // right interest rate from the table based on the given credit score
    // FinalExam - obviously change the return value

    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    int rateGet = 0;
    try {
      tx = session.beginTransaction();

      Query query = session.createQuery("from RateDomainModel where MinCreditScore = :cs ");
      query.setParameter("cs", GivenCreditScore);

      List<?> list = query.list();
      rateGet = (Integer) list.get(0);

      tx.commit();
    } catch (HibernateException e) {
      if (tx != null) tx.rollback();
      e.printStackTrace();
    } finally {
      session.close();
    }
    return rateGet;
  }
コード例 #11
0
ファイル: Topic.java プロジェクト: LennartC/CQ2-Sim
  public static boolean needsHighlight(Topic t, User u) {
    boolean highlight = true;
    Transaction tx = null;
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try {
      tx = session.getTransaction();
      Query q =
          session.createQuery(
              "select ls "
                  + "  from LastseenTopic as ls "
                  + " where ls.userID = :userID "
                  + "   and ls.topicID = :topicID "
                  + "   and ls.lasttime > :lastedit");
      q.setInteger("userID", u.getId());
      q.setInteger("topicID", t.getTopicID());
      q.setDate("lastedit", t.getLastedit());
      List<LastseenTopic> lsts = q.list();
      if (lsts.size() > 0) {
        highlight = lsts.get(0).getLasttime().before(t.getLastedit());
      }

    } catch (HibernateException e) {
      e.printStackTrace();
      if (tx != null && tx.isActive()) tx.rollback();
    }
    return highlight;
  }
コード例 #12
0
 @SuppressWarnings("unchecked")
 @Override
 public List<Sales> getPendingSalesBetween(Date startDate, Date endDate) throws Exception {
   Session session = HibernateUtil.startSession();
   Criteria criteria = session.createCriteria(Sales.class);
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
   List<Sales> sales = new ArrayList<Sales>();
   try {
     Date lowerBound = DateTool.getTomorrowDate(DateTool.getDateWithoutTime(startDate));
     Date upperBound = DateTool.getDateWithoutTime(endDate);
     sales =
         criteria
             .add(Restrictions.ge("date", lowerBound))
             .add(Restrictions.lt("date", upperBound))
             .add(Restrictions.eq("valid", true))
             .add(Restrictions.isNull("inventorySheetData"))
             .addOrder(Order.desc("date"))
             .list();
   } catch (HibernateException ex) {
     ex.printStackTrace();
   } finally {
     session.close();
   }
   return sales;
 }
コード例 #13
0
ファイル: VehicleEvent.java プロジェクト: skibu/core
  /**
   * Reads in all VehicleEvents from the database that were between the beginTime and endTime.
   *
   * @param agencyId Which project getting data for
   * @param beginTime Specifies time range for query
   * @param endTime Specifies time range for query
   * @param sqlClause Optional. Can specify an SQL clause to winnow down the data, such as "AND
   *     routeId='71'".
   * @return
   */
  public static List<VehicleEvent> getVehicleEvents(
      String agencyId, Date beginTime, Date endTime, String sqlClause) {
    IntervalTimer timer = new IntervalTimer();

    // Get the database session. This is supposed to be pretty light weight
    Session session = HibernateUtils.getSession(agencyId);

    // Create the query. Table name is case sensitive and needs to be the
    // class name instead of the name of the db table.
    String hql =
        "FROM VehicleEvent " + "    WHERE time >= :beginDate " + "      AND time < :endDate";
    if (sqlClause != null) hql += " " + sqlClause;
    Query query = session.createQuery(hql);

    // Set the parameters
    query.setTimestamp("beginDate", beginTime);
    query.setTimestamp("endDate", endTime);

    try {
      @SuppressWarnings("unchecked")
      List<VehicleEvent> vehicleEvents = query.list();
      logger.debug("Getting VehicleEvents from database took {} msec", timer.elapsedMsec());
      return vehicleEvents;
    } catch (HibernateException e) {
      logger.error(e.getMessage(), e);
      return null;
    } finally {
      // Clean things up. Not sure if this absolutely needed nor if
      // it might actually be detrimental and slow things down.
      session.close();
    }
  }
コード例 #14
0
ファイル: GetDictionary.java プロジェクト: nykma/ykt4sungard
 /**
  * Copyright (C), 2000-2006, Kingstar Co., Ltd.<br>
  * File name: .java<br>
  * Description: GetDictionary取得一级单位列表<br>
  * Return: List<br>
  * Modify History: <br>
  * 操作类型 操作人 操作时间 操作内容<br>
  * ======================================<br>
  * 创建 韩纪伟 2006-4-4 <br>
  *
  * @author 韩纪伟
  * @version
  * @since 1.0
  */
 public static List getDeptList() {
   DictionaryDAO dao = DictionaryDAO.getInstance();
   List custList = null;
   List deptList = new ArrayList();
   try {
     custList = dao.getDeptList();
     int custsize = custList.size();
     for (int i = 0; i < custsize; i++) {
       Object[] objects = (Object[]) custList.get(i);
       HashMap confMap = new HashMap();
       confMap.put("deptCode", new Integer(convent(objects[0])));
       confMap.put("deptName", convent(objects[1]));
       // confMap.put("pym",GetCh2Spell.getBeginCharacter(convent(objects[1])));
       confMap.put("pym", new GetCh2Spell().String2Alpha(convent(objects[1])));
       deptList.add(confMap);
     }
   } catch (HibernateException he) {
     he.printStackTrace();
   } finally {
     closeSession();
   }
   Collections.sort(deptList, new SortListColl());
   // Arrays.sort(deptList);
   // System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++"+deptList);
   return deptList;
 }
コード例 #15
0
 @SuppressWarnings("unchecked")
 /**
  * @return List<Veiculo>
  *     <p>Método retorna uma lista de usuarios
  */
 public List<Ordem> listar() {
   Session sessao = null;
   Transaction transacao = null;
   List<Ordem> resultado = null;
   try {
     sessao = HibernateUtil.getSessionFactory().openSession();
     transacao = sessao.beginTransaction();
     resultado = sessao.createCriteria(OrdemDeServico.class).list();
     transacao.commit();
     return resultado;
   } catch (HibernateException e) {
     throw new ExceptionInInitializerError(
         "Não foi possível listar os veiculos. Erro: " + e.getMessage());
   } finally {
     try {
       sessao.close();
     } catch (Throwable e) {
       throw new ExceptionInInitializerError(
           "Erro ao fechar a operação consulta em veiculo. Erro: " + e.getMessage());
     }
   }
 }
コード例 #16
0
ファイル: UserDAO.java プロジェクト: muraleekrish/pric
 public UserGroupVO getUserGrp11(String userId) throws Exception {
   UserGroupVO objUserGrpVO = null;
   Criteria objCriteria = null;
   Session objSession = null;
   try {
     logger.info("GET USERGROUP DETAILS OF " + userId);
     objSession = HibernateUtil.getSession();
     objCriteria = objSession.createCriteria(UserGroupVO.class);
     // objCriteria.add(Restrictions.idEq())
     List lstCust = objCriteria.list();
     if (lstCust.size() > 0) {
       objUserGrpVO = (UserGroupVO) lstCust.get(0);
     }
     logger.info("GET USERS ENDS");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET A USERGROUP", e);
     e.printStackTrace();
     throw new HibernateException(e.toString());
   } catch (Exception e) {
     logger.error("GENERAL EXCEPTION DURING GET A USERGROUP", e);
     e.printStackTrace();
     throw new Exception(e.toString());
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return objUserGrpVO;
 }
コード例 #17
0
 public ServiceProduct getServiceProductBySpId(String productId) {
   //        ServiceProduct sp=new ServiceProduct();
   List list = null;
   Session session = getSession();
   try {
     String sql =
         "select sp.csp_id from service_product sp,product p where p.id = sp.product_id and p.MOBILE_PRODUCT = 1";
     Query query = session.createSQLQuery(sql);
     list = query.list();
   } catch (DataAccessResourceFailureException e) {
     logger.error("Hibernate错误:" + e.getMessage());
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   } catch (IllegalStateException e) {
     logger.error("Hibernate错误:" + e.getMessage());
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   } catch (HibernateException e) {
     logger.error("Hibernate错误:" + e.getMessage());
     e.printStackTrace();
   } finally {
     session.close();
   }
   //        return list==null||list.size() == 0?null:list.get(0);
   return null;
 }
コード例 #18
0
ファイル: UserDAO.java プロジェクト: muraleekrish/pric
 private int getMenuId(String menuName) {
   MenuItemsVO objMenuItemsVO = null;
   Criteria objCriteria = null;
   Session objSession = null;
   int menuItemId = 0;
   try {
     logger.info("GETTING MENU ID");
     objSession = HibernateUtil.getSession();
     objCriteria = objSession.createCriteria(MenuItemsVO.class);
     objCriteria.add(Restrictions.eq("menuItemName", menuName));
     List lstMenuItems = objCriteria.list();
     if (lstMenuItems.size() > 0 && lstMenuItems != null) {
       objMenuItemsVO = (MenuItemsVO) lstMenuItems.get(0);
       menuItemId = objMenuItemsVO.getMenuItemID();
     }
     logger.info("GET MENU ID ENDS");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GETMENUID", e);
     e.printStackTrace();
   } catch (Exception e) {
     logger.error("GENERAL EXCEPTION DURING GETMENUID", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return menuItemId;
 }
コード例 #19
0
ファイル: DbHelper.java プロジェクト: Yogitha6/Campus-Talk
 @Override
 public List<Reply> getRepliesToPost(int postId) {
   // TODO Auto-generated method stub
   Session session = sessionFactory.openSession();
   Transaction tx = null;
   List<Reply> replyArr = new ArrayList<Reply>();
   try {
     tx = session.beginTransaction();
     Query query =
         session.createQuery("from Reply where postId = :postId order by createdDate desc");
     query.setParameter("postId", postId);
     replyArr = query.list();
     /*			for(Reply reply : replyArr){
     	System.out.println("Reply - id----"+reply.getReplyId());
     	System.out.println("Reply - Description----"+reply.getDescription());
     	System.out.println("Reply - Post id----"+reply.getPostId());
     }*/
   } catch (HibernateException e) {
     if (tx != null) {
       tx.rollback();
       e.printStackTrace();
     }
   } finally {
     session.close();
   }
   return replyArr;
 }
コード例 #20
0
ファイル: UserDAO.java プロジェクト: muraleekrish/pric
 public Collection getParentTypeUsers(int userTypeId) {
   Session objSession = null;
   List objList = null;
   try {
     logger.info("GETTING PARENT TYPE USERS");
     objSession = HibernateUtil.getSession();
     Query objQuery =
         objSession.createQuery(
             "select users.userId, users.firstName, users.lastName from UserTypesVO as userTypes, UsersVO as users  where userTypes.userTypeId = ? and userTypes.parentUserType.userTypeId = users.userTypes.userTypeId order by users.firstName");
     objQuery.setInteger(0, userTypeId);
     objList = objQuery.list();
     Iterator itr = objList.iterator();
     objList = new ArrayList();
     while (itr.hasNext()) {
       Object[] innerRow = (Object[]) itr.next();
       UsersVO objUsersVO = new UsersVO();
       objUsersVO.setUserId(String.valueOf(innerRow[0]));
       objUsersVO.setFirstName(String.valueOf(innerRow[1]));
       objUsersVO.setLastName(String.valueOf(innerRow[2]));
       objList.add(objUsersVO);
     }
     logger.info("GET PARENT TYPE USERS ENDS");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET PARENT TYPE USERS", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return objList;
 }
コード例 #21
0
ファイル: DbHelper.java プロジェクト: Yogitha6/Campus-Talk
  public int getCountOfSubscribers(int forumId, int userId) {
    // TODO Auto-generated method stub
    Session session = this.sessionFactory.openSession();
    Transaction tx = null;
    int countOfSubscribers = 0;
    try {
      tx = session.beginTransaction();
      Query query = null;
      if (userId == 0) {
        query = session.createQuery("select count(*) from Subscription where forumId = :forumId");
        query.setParameter("forumId", forumId);
      } else {
        query =
            session.createQuery(
                "select count(*) from Subscription where forumId = :forumId and userId = :userId");
        query.setParameter("forumId", forumId);
        query.setParameter("userId", userId);
      }

      Long count = (Long) query.uniqueResult();
      countOfSubscribers = count.intValue();
      // System.out.println("No of subscribers.."+countOfSubscribers);
    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return countOfSubscribers;
  }
コード例 #22
0
ファイル: UserDAO.java プロジェクト: muraleekrish/pric
 public List getAllUsers() {
   Criteria objCriteria = null;
   Session objSession = null;
   List objList = null;
   try {
     logger.info("GETTING ALL USERS");
     objSession = HibernateUtil.getSession();
     objCriteria =
         objSession
             .createCriteria(UsersVO.class)
             .add(Restrictions.eq("valid", new Boolean(true)))
             .addOrder(Order.asc("firstName"));
     objCriteria.addOrder(Order.asc("userId"));
     objList = objCriteria.list();
     logger.info("GET ALL USERS ENDS");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL USERS", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return objList;
 }
コード例 #23
0
ファイル: DbHelper.java プロジェクト: Yogitha6/Campus-Talk
  @Override
  public List<Forum> getForumsOfaUser(int userId) {
    // TODO Auto-generated method stub
    List<Forum> forums = new ArrayList<Forum>();
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      Query query = session.createQuery("from Subscription where userId = :userId");
      query.setString("userId", String.valueOf(userId));
      List<Subscription> userSubscribedGroups = query.list();
      for (Subscription subsc : userSubscribedGroups) {
        query = session.createQuery("from Forum where forumId = :forumId");
        query.setParameter("forumId", subsc.getForumId());
        // add this to a list variable query.uniqueResult();
        forums.add((Forum) query.uniqueResult());
      }

    } catch (HibernateException e) {
      if (tx != null) {
        tx.rollback();
        e.printStackTrace();
      }
    } finally {
      session.close();
    }
    return forums;
  }
コード例 #24
0
ファイル: UserDAO.java プロジェクト: muraleekrish/pric
 public List getChildPersons(String userId, boolean withSelfUser) {
   Criteria objCriteria = null;
   Session objSession = null;
   List objList = null;
   try {
     logger.info("GETTING ALL USERS");
     objSession = HibernateUtil.getSession();
     objCriteria =
         objSession.createCriteria(UsersVO.class).add(Restrictions.eq("valid", new Boolean(true)));
     if (withSelfUser)
       objCriteria.add(
           Restrictions.or(
               Restrictions.eq("userId", userId), Restrictions.eq("parentUser.userId", userId)));
     else objCriteria.add(Restrictions.eq("parentUser.userId", userId));
     objCriteria.addOrder(Order.asc("userId"));
     objList = objCriteria.list();
     logger.info("GET ALL USERS ENDS");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL USERS", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return objList;
 }
コード例 #25
0
  public IKategorie getKategorie(String kategorieName) throws DatabaseEntryNotFoundException {

    IKategorie kategorie = null;

    try {
      Session session = HibernateHelper.getSession();
      Query query =
          session.createQuery("from " + getTable() + " k where k.bezeichnung = :kategorieName");
      query.setString("kategorieName", kategorieName);

      @SuppressWarnings("rawtypes")
      List results = query.list();

      if (results.size() == 1) {
        kategorie = (IKategorie) results.get(0);
      }

      if (results.size() == 0) {
        throw new DatabaseEntryNotFoundException();
      }

    } catch (HibernateException e) {
      e.printStackTrace();
    }

    return kategorie;
  }
コード例 #26
0
  /* (non-Javadoc)
   * @see com.kp.marsh.ebt.server.importer.dao.impl.ImportController#findInformationOwnerByEysCode(java.lang.String)
   */
  @Override
  public InformationOwners findInformationOwnerByEysCode(String codEys) throws Exception {

    InformationOwners result = null;
    Session session = (Session) this.connection.getSessionFactory().openSession();

    Transaction tx = session.beginTransaction();
    try {

      Query q = session.createQuery("from InformationOwners where cod_Eys =:codEys");
      q.setParameter("codEys", codEys);
      List<InformationOwners> queryResList = q.list();
      tx.commit();
      if (queryResList.size() == 1) {
        result = queryResList.get(0);
      } else if (queryResList.size() > 1) {
        throw new Exception(
            "There should be only one InformationOwner with codEys ="
                + codEys
                + "- "
                + queryResList.get(0).getDescription());
      }

    } catch (HibernateException ex) {
      log.error("Exception in findInformationOwnerById()");
      ex.printStackTrace();
      tx.rollback();
    } finally {
      session.close();
    }

    return result;
  }
コード例 #27
0
  public void updateStaff(StaffEntity staff) {
    Session session = SessionFactoryProvider.getSessionFactory().openSession();

    Transaction dbTransaction = null;
    try {
      dbTransaction = session.beginTransaction();

      StaffEntity staffUpdate = (StaffEntity) session.get(StaffEntity.class, staff.getStaffId());

      log.info("Updating: " + staffUpdate.toString());

      staffUpdate.setFireNumber(staff.getFireNumber());
      staffUpdate.setFirstName(staff.getFirstName());
      staffUpdate.setLastName(staff.getLastName());
      staffUpdate.setRank(staff.getRank());
      staffUpdate.setHireDate(staff.getHireDate());
      staffUpdate.setTermDate(staff.getTermDate());
      staffUpdate.setDepartmentId(staff.getDepartmentId());

      session.update(staffUpdate);
      dbTransaction.commit();

    } catch (HibernateException error) {
      if (dbTransaction != null) dbTransaction.rollback();
      error.printStackTrace();
    } finally {
      session.close();
    }
  }
コード例 #28
0
 /* (non-Javadoc)
  * @see com.kp.marsh.ebt.server.importer.dao.impl.ImportController#findMarshCredentialByADUsername(java.lang.String)
  */
 @Override
 public MarshPeopleCredentials findMarshCredentialByADUsername(String username) throws Exception {
   MarshPeopleCredentials result = null;
   Session session = (Session) this.connection.getSessionFactory().openSession();
   Transaction tx = session.beginTransaction();
   try {
     Query q = session.createQuery("from MarshPeopleCredentials where username =:username");
     q.setParameter("username", username);
     List<MarshPeopleCredentials> queryResList = q.list();
     tx.commit();
     if (queryResList.size() == 1) {
       result = queryResList.get(0);
     } else if (queryResList.size() > 1) {
       throw new Exception(
           "There should be only one MarshPeopleCredentials with username ="******"- "
               + queryResList.get(0).getUsername());
     }
   } catch (HibernateException ex) {
     log.error("Exception in findMarshCredentialByADUsername()");
     ex.printStackTrace();
     tx.rollback();
   } finally {
     session.close();
   }
   return result;
 }
コード例 #29
0
ファイル: RateCodesDAO.java プロジェクト: muraleekrish/pric
 public Collection getAllRateCodes(int tdspId) {
   /**
    * Requires - Modifies - Effects -
    *
    * @throws -
    */
   Criteria objCriteria = null;
   Session objSession = null;
   List objList = null;
   try {
     logger.info("GETTING ALL RATE CODES BY TDSP ID");
     objSession = HibernateUtil.getSession();
     objCriteria =
         objSession
             .createCriteria(RateCodesVO.class)
             .add(Restrictions.eq("tdsp.tdspIdentifier", new Integer(tdspId)));
     objCriteria.addOrder(Order.asc("rateCode"));
     objList = objCriteria.list();
     logger.info("GOT ALL RATE CODES BY TDSP ID");
   } catch (HibernateException e) {
     logger.error("HIBERNATE EXCEPTION DURING GET ALL RATE CODES BY TDSP ID", e);
     e.printStackTrace();
   } finally {
     if (objSession != null) {
       objSession.close();
     }
   }
   return objList;
 }
コード例 #30
0
  /**
   * Method to add user to the database
   *
   * @param user User object reference
   * @return userId
   */
  public Integer addUser(User user) {

    beginSession();
    Transaction transaction = null;
    Integer userId = null;

    try {

      transaction = session.beginTransaction();
      userId = (Integer) session.save(user);
      transaction.commit();

    } catch (HibernateException e) {

      e.printStackTrace();

      if (transaction != null) {

        transaction.rollback();
      }
    } finally {
      session.close();
    }

    return userId;
  }