@Override public List<Category> getInterestCategory(List<Integer> interestIds) { List<Category> categories = new ArrayList<Category>(); Session session = HibernateUtils.getSession();//生成Session实例 Transaction tx = session.beginTransaction();//生成事务实例 try { ListToString listToString = new ListToString(); String idString = listToString.getListToString(interestIds); String hql = "select new Category(category_id,category_name) from Category"; String hql2 = " where category_id in " +idString; if (!idString.equals("")) { Query query = session.createQuery(hql+hql2); categories = query.list(); tx.commit(); } //调用session的get()方法,找到此用户到内存中 } catch (Exception e) { e.printStackTrace(); tx.rollback();//事务回滚 }finally{ HibernateUtils.closeSession();//关闭session实例 } return categories; }
/** * Checks that combination of Instructor/Dept * does not already exist * @param frm * @return */ protected boolean isDeptInstructorUnique( InstructorEditForm frm, HttpServletRequest request ) { String query = "from DepartmentalInstructor " + "where externalUniqueId=:puid and department.uniqueId=:deptId"; if (frm.getInstructorId()!=null && frm.getInstructorId().trim().length()>0) { query += " and uniqueId!=:uniqueId"; } DepartmentalInstructorDAO ddao = new DepartmentalInstructorDAO(); org.hibernate.Session hibSession = ddao.getSession(); HttpSession httpSession = request.getSession(); String deptId = (String) httpSession.getAttribute(Constants.DEPT_ID_ATTR_NAME); Query q = hibSession.createQuery(query); q.setString("puid", frm.getPuId().trim()); q.setLong("deptId", Long.parseLong(deptId)); if (frm.getInstructorId()!=null && frm.getInstructorId().trim().length()>0) { q.setString("uniqueId", frm.getInstructorId().trim()); } return (q.list().size()==0); }
@Override @Transactional(propagation = Propagation.MANDATORY) public void deleteForTaxonomy(final Taxonomy taxonomy) { getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) { Query query = session .createQuery("delete from TermAttributes ta where ta.term.id in (from Term where taxonomy = :taxonomy)"); query.setParameter("taxonomy", taxonomy); query.executeUpdate(); query = session.createQuery("delete from Term where taxonomy = :taxonomy"); query.setParameter("taxonomy", taxonomy); query.executeUpdate(); return null; } }); }
/** * * @param hql传入的hql语句 * @param pageCode当前页 * @param pageSize每页显示大小 * @return */ public List doSplitPage(final String hql,final int pageCode,final int pageSize){ //调用模板的execute方法,参数是实现了HibernateCallback接口的匿名类, return (List) this.getHibernateTemplate().execute(new HibernateCallback(){ //重写其doInHibernate方法返回一个object对象, public Object doInHibernate(Session session) throws HibernateException, SQLException { //创建query对象 Query query=session.createQuery(hql); //返回其执行了分布方法的list return query.setFirstResult((pageCode-1)*pageSize).setMaxResults(pageSize).list(); } }); }
@Override @SuppressWarnings("unchecked") protected void executeDataMigration(HibernateMigrationHelper helper, MigrationResult result, Session session) throws Exception { // System SMTP settings Query query = session.createQuery("FROM SystemConfig WHERE key = 'smtppassword'"); List<FakeSystemConfig> sysconf = query.list(); if( !Check.isEmpty(sysconf) ) { FakeSystemConfig sc = sysconf.get(0); // Should only be one String encpwd = encryptionService.encrypt(sc.value); sc.value = encpwd; session.save(sc); result.incrementStatus(); } // The end session.flush(); session.clear(); }
@Override @Transactional(propagation = Propagation.MANDATORY) public int deleteAllForUserKeyReasons(final ItemKey itemKey, final String userId, final Collection<String> reasons) { return ((Number) getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) { if( Check.isEmpty(reasons) ) { return Integer.valueOf(0); } Query query = session.createQuery( "delete from Notification where itemid = :itemkey and userTo = :user and reason in (:reasons) and institution = :inst"); query.setParameter(ITEMKEY, itemKey.toString()); query.setParameter(USER, userId); query.setParameterList(REASONS, reasons); query.setParameter(INST, CurrentInstitution.get()); return query.executeUpdate(); } })).intValue(); }
@SuppressWarnings("unchecked") private void deleteSystemUrl(String parentId,Session session){ List<Url> urls=session.createQuery("from "+Url.class.getName()+" where parentId=:parentId").setString("parentId", parentId).list(); session.createQuery("delete "+Url.class.getName()+" where parentId=:parentId").setString("parentId", parentId).executeUpdate(); for(Url url:urls){ int count=0; Query countQuery=session.createQuery("select count(*) from "+Url.class.getName()+" where parentId=:parentId").setString("parentId", url.getId()); Object countObj=countQuery.uniqueResult(); if(countObj instanceof Long){ count=((Long)countObj).intValue(); }else if(countObj instanceof Integer){ count=((Integer)countObj).intValue(); } if(count>0){ deleteSystemUrl(url.getId(),session); } } }
/** * 查询target里面指定的字段 * * @param <T> 要查询的实体类 * * @param t 要查询的类 * @param pageSize * @param currentPage * @param constraint 查询条件 * @param desc * @param asc * @param queryRecordCount 是否查询总记录数(记录很多时查询较费时间),若传false,则返回的page实体类的记录数为Long.MAX_VALUE,<br> * 前端可做无限分页 * @param selectField 要查询的字段,若不传,则查询该类所有字段,page里面放的是实体类,否则放的是map,不过map里面的key的'.'会被替换成'__'<br> * (这个是可变参数,没有请不传,切忌传null!) * @return */ public final static <T> Page<T> listCustomField(Class<?> t,int pageSize,int currentPage,Map<String, Object> constraint, List<String> desc,List<String> asc,boolean queryRecordCount,String[] groupBy,String... selectField){ try { StringBuffer hql = getSelectHql(t, constraint, desc, asc, groupBy, selectField); Long recordCount = Long.MAX_VALUE; if (queryRecordCount) { recordCount = getRecordCount(constraint, hql); } Query query = createQuery(constraint,hql); faging(pageSize,currentPage, query); @SuppressWarnings("unchecked") List<T> list = query.list(); return setPage(currentPage, recordCount, pageSize, list); } catch (Exception e) { setException(e); return null; }finally{ closeSession(); } }
/** * 获取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; }
@Override public Integer getCountRoleForOrg(Integer roleId, Integer orgId, String searchPhrase) { StringBuilder queryTextBuilder = new StringBuilder(RoleDAO.COUNT_ROLE_FOR_ORG); if (!StringUtils.isBlank(searchPhrase)) { String[] tokens = searchPhrase.trim().split("\\s+"); for (String token : tokens) { queryTextBuilder.append(" AND (uor.userOrganisation.user.firstName LIKE '%").append(token) .append("%' OR uor.userOrganisation.user.lastName LIKE '%").append(token) .append("%' OR uor.userOrganisation.user.login LIKE '%").append(token).append("%')"); } } Query query = getSession().createQuery(queryTextBuilder.toString()); query.setInteger("roleId", roleId.intValue()); query.setInteger("orgId", orgId.intValue()); Object value = query.uniqueResult(); return new Integer(((Number) value).intValue()); }
@SuppressWarnings({ "rawtypes", "unchecked" }) public final static Page getQueryResult(String hql,String domainSimpleName, Map<String,Object> map,int pageSize,int currentPage){ try { StringBuffer sb = new StringBuffer(hql); if (map != null && domainSimpleName != null) { appendHqlWhere(domainSimpleName, sb, map); } Long recordCount = getRecordCount(map, sb); Query createQuery = getSession().createQuery(sb.toString()); if (map != null) { setMapParam(map, createQuery); } faging(pageSize, currentPage, createQuery); return setPage(currentPage, recordCount, pageSize, createQuery.list()); //return createQuery.list(); } catch (Exception e) { setException(e); return null; }finally{ closeSession(); } }
@Override @Transactional public ActivateRequest getLastActive(final String type, final Item item, final String attachment) { return (ActivateRequest) getHibernateTemplate().execute(new HibernateCallback() { @Override @Transactional public Object doInHibernate(Session session) { Query query = session.createQuery("from ActivateRequest req" + " where req.type = :type and req.item = :item and req.attachment = :att and req.status = :status" + " order by req.until desc"); query.setFetchSize(1); query.setFirstResult(0); query.setString("type", type); query.setString("att", attachment); query.setEntity("item", item); query.setInteger("status", ActivateRequest.TYPE_ACTIVE); List<?> l = query.list(); return l.size() == 0 ? null : l.get(0); } }); }
public static List<TimePattern> findAll(Long sessionId, Boolean visible) { String query = "from TimePattern tp " + "where tp.session.uniqueId=:sessionId"; if (visible!=null) query += " and visible=:visible"; org.hibernate.Session hibSession = new TimePatternDAO().getSession(); Query q = hibSession.createQuery(query); q.setCacheable(true); q.setLong("sessionId", sessionId.longValue()); if (visible!=null) q.setBoolean("visible", visible.booleanValue()); List<TimePattern> v = q.list(); Collections.sort(v); return v; }
/** * Prepare the given Query object, applying cache settings and/or * a transaction timeout. * @param queryObject the Query object to prepare * @see #setCacheQueries * @see #setQueryCacheRegion */ protected void prepareQuery(Query queryObject) { if (isCacheQueries()) { queryObject.setCacheable(true); if (getQueryCacheRegion() != null) { queryObject.setCacheRegion(getQueryCacheRegion()); } } if (getFetchSize() > 0) { queryObject.setFetchSize(getFetchSize()); } if (getMaxResults() > 0) { queryObject.setMaxResults(getMaxResults()); } SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory()); if (sessionHolder != null && sessionHolder.hasTimeout()) { queryObject.setTimeout(sessionHolder.getTimeToLiveInSeconds()); } }
@Override public List<User> getAllUsers(int start,int num) { List<User> users = new ArrayList<User>(); Session session = HibernateUtils.getSession();//生成Session实例 Transaction tx = session.beginTransaction();//生成事务实例 try { Query query = session.createQuery("select new User(user_id,username,tel_num,integral,accuracy,is_frozen) from User order by user_id"); query.setFirstResult(start-1); System.out.println(start-1); System.out.println(num); query.setMaxResults(num); users = query.list(); tx.commit();//提交事务 } catch (Exception e) { e.printStackTrace(); tx.rollback(); }finally { HibernateUtils.closeSession();//关闭session实例 } return users; }
private int countElements (final String table, final Long pid) { return dao.getHibernateTemplate ().execute ( new HibernateCallback<Integer> () { @Override public Integer doInHibernate (Session session) throws HibernateException, SQLException { String sql = "SELECT count(*) FROM " + table + " WHERE PRODUCT_ID = ?"; Query query = session.createSQLQuery (sql).setLong (0, pid); return ((BigInteger) query.uniqueResult ()).intValue (); } }); }
@Override public int update(List<Integer> ids) { Session session = null; try { session = this.sessions.openSession(); // 设置状态 为更新 // 需要重新索引 String hql = "update AppHistory4Index set appStatus=2,indexStatus=0,lastOpTime=:lastOpTime where appId in (:appIds)"; Query query = session.createQuery(hql); query.setParameterList("appIds", ids); query.setTimestamp("lastOpTime", new Date()); return query.executeUpdate(); } catch (Exception e) { logger.error("error:", e); return 0; } finally { if (session != null && session.isOpen()) { session.flush(); session.clear(); session.close(); } } }
@Override public Page<T> findPage(final PageRequest pageRequest, String hql) { AssertUtils.notNull(pageRequest, "pageRequest不能为空"); Page<T> page = new Page<T>(pageRequest); if (pageRequest.isCountTotal()) { long totalCount = countHqlResult(hql); page.setTotalItems(totalCount); } if (pageRequest.isOrderBySetted()) { hql = setOrderParameterToHql(hql, pageRequest); } Query q = createQuery(hql); setPageParameterToQuery(q, pageRequest); List result = q.list(); page.setResult(result); return page; }
@SuppressWarnings("unchecked") @Override public int getCountActiveCoursesByUser(Integer userId, boolean isSysadmin, String searchString) { final String GET_ALL_ACTIVE_COURSE_IDS = "SELECT COUNT(o) FROM Organisation o" + " WHERE o.organisationType.organisationTypeId = " + OrganisationType.COURSE_TYPE + " AND o.organisationState.organisationStateId = " + OrganisationState.ACTIVE + " AND (o.name LIKE CONCAT('%', :searchString, '%'))"; final String GET_ACTIVE_COURSE_IDS_BY_USER = "SELECT COUNT(uo)" + " FROM UserOrganisation uo " + " WHERE uo.organisation.organisationType.organisationTypeId = " + OrganisationType.COURSE_TYPE + " AND uo.organisation.organisationState.organisationStateId = " + OrganisationState.ACTIVE + " AND uo.user.userId = :userId " + " AND (uo.organisation.name LIKE CONCAT('%', :searchString, '%'))"; String queryStr = isSysadmin ? GET_ALL_ACTIVE_COURSE_IDS : GET_ACTIVE_COURSE_IDS_BY_USER; Query query = getSession().createQuery(queryStr); // support for custom search from a toolbar searchString = searchString == null ? "" : searchString; query.setString("searchString", searchString); if (!isSysadmin) { query.setInteger("userId", userId); } return ((Number) query.uniqueResult()).intValue(); }
@SuppressWarnings("unchecked") private FakeAccessExpression getOrCreateExpression(Session session, Query exprQuery, String expression) { List<FakeAccessExpression> list = exprQuery.setParameter("expression", expression).list(); //$NON-NLS-1$ if( !list.isEmpty() ) { return list.get(0); } else { FakeAccessExpression result = new FakeAccessExpression(); result.setExpression(expression); result.parseExpression(); session.save(result); return result; } }
@Override public int bulkUpdate(final String queryString, final Object... values) throws DataAccessException { return executeWithNativeSession(new HibernateCallback<Integer>() { @Override public Integer doInHibernate(Session session) throws HibernateException { Query queryObject = session.createQuery(queryString); prepareQuery(queryObject); if (values != null) { for (int i = 0; i < values.length; i++) { queryObject.setParameter(i, values[i]); } } return queryObject.executeUpdate(); } }); }
@Override public int getCountVisitLogsBySessionAndItem(Long sessionId, Long itemUid, String searchString) { String COUNT_USERS_BY_SESSION_AND_ITEM = "SELECT COUNT(*) FROM " + ResourceItemVisitLog.class.getName() + " visit WHERE visit.sessionId = :sessionId AND visit.resourceItem.uid = :itemUid" + " AND (CONCAT(visit.user.lastName, ' ', visit.user.firstName) LIKE CONCAT('%', :searchString, '%')) "; Query query = getSession().createQuery(COUNT_USERS_BY_SESSION_AND_ITEM); query.setLong("sessionId", sessionId); query.setLong("itemUid", itemUid); // support for custom search from a toolbar searchString = searchString == null ? "" : searchString; query.setString("searchString", searchString); List list = query.list(); if ((list == null) || (list.size() == 0)) { return 0; } else { return ((Number) list.get(0)).intValue(); } }
@Override public void loadDataUsingParent() { Session ses=null; Query query=null; List<User> list=null; Set<PhoneNumber> childs=null; //get Session ses=HibernateUtil.getSession(); //create Query obj query=ses.createQuery("from User"); //execute Query list=query.list(); //process the Results for(User user:list){ System.out.println("parent---->"+user); //get all childs of each parent childs=user.getPhones(); System.out.println(childs.size()); for(PhoneNumber ph:childs){ System.out.println("child--->"+ph); }//for }//for }
@Override public Map<Integer, com.kingsoft.sjk.po.Catalog> initCatalog() { Session session = null; List<Catalog> list = null; int updateInt = 0; Map<Integer, Catalog> catalogs = new HashMap<Integer, Catalog>(); try { session = this.sessionFactory.openSession(); Query q = session.createQuery("from Catalog"); list = HibernateHelper.list(q); for (Catalog catalog : list) { catalogs.put(catalog.getId(), catalog); } } catch (Exception e) { logger.error("error:", e); } finally { list.clear(); session.close(); } return catalogs; }
@Override @SuppressWarnings("unchecked") @Transactional(propagation = Propagation.MANDATORY) public List<AccessEntry> listAll() { return getHibernateTemplate().executeFind(new TLEHibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException { Query query = session.getNamedQuery("getAllEntriesForInstitution"); query.setParameter("institution", CurrentInstitution.get()); return query.list(); } }); }
@Override public Collect getCollectByBook$User(int bookId, int userId) { String sql = "from Collect where bookId=:bookId and userId=:userId"; Session session = sessionFactory.getCurrentSession(); Query query = session.createQuery(sql); query.setInteger("bookId", bookId); query.setInteger("userId", userId); List<Collect> collects = query.list(); if(collects.size() == 0) return null; return collects.get(0); }
/** * * @param deptCode * @return */ public static List getStaffByDept(String deptCode, Long acadSessionId) throws Exception { if (deptCode == null){ return(null); } Query q = StaffDAO.getInstance().getSession().createQuery( "select distinct s from Staff s where s.dept=:deptCode and " + "(select di.externalUniqueId from DepartmentalInstructor di " + "where di.department.deptCode=:deptCode and di.department.session.uniqueId=:sessionId and di.externalUniqueId = s.externalUniqueId ) is null"); q.setString("deptCode", deptCode); q.setLong("sessionId", acadSessionId); q.setCacheable(true); return (q.list()); }
/** * 获取符合查询条件的记录数 * @param target 要查询的实体类 * @param where 查询条件 * @return 符合查询条件的记录数 */ public final static long getCount(Class<? extends BaseRelationalDatabaseDomain> target,Map<String, Object> where){ try { Query query = getSession().createQuery(getCountHql(getSelectHql(target, where, null, null)).toString()); setMapParam(where, query); return (Long) query.uniqueResult(); } catch (Exception e) { setException(e); return -1; }finally{ closeSession(); } }
@Override public AssessmentResult getLastAssessmentResult(Long assessmentUid, Long userId) { Query q = getSession().createQuery(FIND_LAST_BY_ASSESSMENT_AND_USER); q.setParameter(0, userId); q.setParameter(1, assessmentUid); return (AssessmentResult) q.uniqueResult(); }
@SuppressWarnings("unchecked") @Override public void findUnitName(PageUtil<Material> pageUtil,Long mId) throws JshException { //多表联查,多表连查,此处用到了createSQLQuery,可以随便写sql语句,很方便, StringBuffer queryString = new StringBuffer(); queryString.append("select jsh_unit.UName from jsh_unit inner join jsh_material on UnitId=jsh_unit.id where jsh_material.id="+mId); Query query; query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(queryString + SearchConditionUtil.getCondition(pageUtil.getAdvSearch())); pageUtil.setTotalCount(query.list().size()); pageUtil.setPageList(query.list()); }
@Override @Transactional(propagation = Propagation.MANDATORY) public void delete(final Term term) { getHibernateTemplate().execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) { final Taxonomy taxonomy = term.getTaxonomy(); final int left = term.getLeft(); final int right = term.getRight(); Query q = session.createQuery("DELETE FROM TermAttributes ta where ta.term.id in (FROM Term" + " WHERE lft BETWEEN :left AND :right AND taxonomy = :taxonomy)"); q.setInteger("left", left); q.setInteger("right", right); q.setParameter("taxonomy", taxonomy); q.executeUpdate(); q = session.createQuery("DELETE FROM Term" + " WHERE lft BETWEEN :left AND :right AND taxonomy = :taxonomy"); q.setInteger("left", left); q.setInteger("right", right); q.setParameter("taxonomy", taxonomy); q.executeUpdate(); decrementLaR(session, taxonomy, right + 1, Integer.MAX_VALUE, right - left + 1); return null; } }); }
public List<?> doFindByNamedQueryAndNamedParam(final String queryName, final String[] paramNames, final Object[] values) { if (values != null && (paramNames == null || paramNames.length != values.length)) { throw new IllegalArgumentException("Length of paramNames array must match length of values array"); } Query queryObject = getSession().getNamedQuery(queryName); if (values != null) { for (int i = 0; i < values.length; i++) { applyNamedParameterToQuery(queryObject, paramNames[i], values[i]); } } return queryObject.list(); }
@Override public long count() { String queryString = new StringBuilder("select count(id) from ").append(getType().getName()).toString(); Query query = getSession().createQuery(queryString); Object o = query.uniqueResult(); return Long.valueOf(o.toString()); }
@Override public int updateToShow(Session session, String marketName) { String hql = "update App set hidden = 0 where marketName = :marketName"; Query query = session.createQuery(hql); query.setParameter("marketName", marketName); return query.executeUpdate(); }
@SuppressWarnings("unchecked") @Override public void find(PageUtil<UserBusiness> pageUtil,String ceshi) throws JshException { Query query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createQuery("select count(id),sum(id) from UserBusiness userBusiness where 1=1 " + SearchConditionUtil.getCondition(pageUtil.getAdvSearch())); pageUtil.setTotalCount(query.list().size()); pageUtil.setPageList(query.list()); }
/** * (non-Javadoc) * * @see org.lamsfoundation.lams.learningdesign.dao.ITransitionDAO#getTransitionByToActivityID(java.lang.Long) */ @Override public Transition getTransitionByToActivityID(Long toActivityID) { if (toActivityID != null) { Query query = getSessionFactory().getCurrentSession().createQuery(FIND_BY_TO_ACTIVITY); query.setLong(0, toActivityID.longValue()); return (Transition) query.uniqueResult(); } return null; }
@SuppressWarnings("unchecked") @Override public void batchSetStatus(Boolean status,String depotHeadIDs) { String sql="update jsh_depothead d set d.Status=" + status + " where d.id in (" + depotHeadIDs + ")"; Query query = this.getHibernateTemplate().getSessionFactory().getCurrentSession().createSQLQuery(sql); query.executeUpdate(); }
/** * @see org.lamsfoundation.lams.lesson.dao.ILessonDAO#getLessonsByOrgAndUserWithCompletedFlag(Integer, Integer, * boolean) */ @Override public List getLessonsByGroupAndUser(Integer userId, Integer orgId) { Query query = getSession().getNamedQuery("lessonsByOrgAndUserWithChildOrgs"); query.setInteger("userId", userId.intValue()); query.setInteger("orgId", orgId.intValue()); List result = query.list(); return result; }
@Override public void removeEntriesBeforeDate(final Date date) { getHibernateTemplate().execute(new DMLPartitioner(getEntityName(), "id") { @Override public String getWhereClause() { return "where timestamp < :date and institution = :institution"; } @Override public void setWhereParams(Query query) { query.setTimestamp("date", date); query.setParameter("institution", CurrentInstitution.get()); } @Override public String getDmlStart() { return "delete from " + getEntityName(); } @Override public void setDmlParams(Query q) { // Nothing additional to set that not already in the where // parameters } }); }