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; }
public void saveEvent(Event event) { Event event1 = getEvent(event); Session session = SessionFactoryUtil.getInstance().getCurrentSession(); try { if (event1 == null) { Transaction transaction = session.beginTransaction(); try { session.save(event); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } } else { Transaction transaction = session.beginTransaction(); try { session.update(event); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } } } finally { if (session.isOpen()) { session.flush(); session.disconnect(); session.close(); } } }
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; }
@SuppressWarnings({"unchecked"}) public void testBasicUsage() { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Stock stock = new Stock(); stock.setStockCode("7052"); stock.setStockName("PADINI"); Category category1 = new Category("CONSUMER", "CONSUMER COMPANY"); // new category, need save to get the id first session.save(category1); StockCategory stockCategory = new StockCategory(); stockCategory.setStock(stock); stockCategory.setCategory(category1); stockCategory.setCreatedDate(new Date()); // extra column stockCategory.setCreatedBy("system"); // extra column stock.getStockCategories().add(stockCategory); session.save(stock); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } }
/* (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; }
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; }
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; }
@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(); } }
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; }
@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; }
@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(); } }
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; }
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; }
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; }
@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; }
/** * 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; }
/** * 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; }
/** * Updates users information in the database * * @param UserId reference to primary key in database * @param address reference to users address * @param email reference to users email * @param phone reference to users phone */ public void updateUser(Integer UserId, String address, String phone, String email, Integer role) { beginSession(); Transaction tx = null; try { tx = session.beginTransaction(); User user = (User) session.get(User.class, UserId); user.setAddress(address); user.setPhone(phone); user.setEmail(email); session.update(user); tx.commit(); } catch (HibernateException e) { e.printStackTrace(); if (tx != null) { tx.rollback(); } } finally { session.close(); } }
@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; }
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; }
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; }
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; }
@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; }
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; }
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; }
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; }
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(); } }
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; }
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; }
/* (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; }