Exemplo n.º 1
1
  // 默认顺序createtime desc
  public List<T> findByMapWithCond(Map<String, Object> params, String orderBy, Boolean asc) {
    StringBuilder hql = new StringBuilder("from " + className);
    String orderStr;
    if (null == orderBy) {
      orderStr = " order by createtime desc";
    } else {
      String ascStr = asc ? " asc" : " desc";
      orderStr = " order by " + orderBy + ascStr;
    }
    Map<String, Object> alterParams = new HashMap<>();
    Query query;
    if (null != params && !params.isEmpty()) {
      hql.append(" where ");
      for (String field : params.keySet()) {
        int i = field.indexOf(" ");
        Assert.isTrue(i != -1, "Wrong condition, must have space inside!");
        String ramdonName = "_" + Utils.getRandomString(8);
        hql.append(field).append(" :").append(ramdonName).append(" and ");
        if (field.contains("like")) {
          String likeStr = "%" + params.get(field) + "%";
          alterParams.put(ramdonName, likeStr);
        } else alterParams.put(ramdonName, params.get(field));
      }
      hql.append("1=1");
      query = getSession().createQuery(hql.append(orderStr).toString());

      for (String field : alterParams.keySet()) query.setParameter(field, alterParams.get(field));

    } else query = getSession().createQuery(hql.append(orderStr).toString());
    return query.list();
  }
Exemplo n.º 2
0
  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;
  }
Exemplo n.º 3
0
 @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();
   }
 }
Exemplo n.º 4
0
 public void deletePublicMessageFor(final Long messageId, final User user) {
   final Query query =
       entityManager.createNativeQuery(
           "delete from PUBLIC_MESSAGES where ID=:id and sender_id=:user_id");
   query.setParameter("user_id", user.getId());
   query.setParameter("id", messageId);
   query.executeUpdate();
 }
Exemplo n.º 5
0
 public void partGroup(final User user, final Long groupId) {
   final Query query =
       entityManager.createNativeQuery(
           "DELETE FROM GROUP_USER WHERE GROUP_ID=:groupId AND USER_ID=:userId");
   query.setParameter("groupId", groupId);
   query.setParameter("userId", user.getId());
   query.executeUpdate();
 }
Exemplo n.º 6
0
 private boolean isGroupMember(final User user, final GroupImpl group) {
   final Query query =
       entityManager.createNativeQuery(
           "select 1 from GROUP_USER where USER_ID=:userId AND GROUP_ID=:groupId");
   query.setParameter("userId", user.getId());
   query.setParameter("groupId", group.getId());
   return query.getResultList().size() > 0;
 }
Exemplo n.º 7
0
 public List<User> fetchUsersBeginningByAndAddableToWorkout(final String prefix, final long id) {
   final Query query =
       entityManager.createQuery(
           "select u from UserImpl u, WorkoutImpl workout where u.name<>'googlebot' AND u.name LIKE CONCAT(:prefix, '%')"
               + " AND u not MEMBER OF workout.participants AND workout.id = :id ");
   query.setParameter("prefix", prefix);
   query.setParameter("id", id);
   return query.getResultList();
 }
Exemplo n.º 8
0
 public void joinGroup(final User user, final Long groupId) {
   final Query query =
       entityManager.createNativeQuery(
           "insert GROUP_USER SET GROUP_ID=:groupId, USER_ID=:userId, JOINING_DATE=:joiningDate, LAST_VISIT=:joiningDate");
   query.setParameter("groupId", groupId);
   query.setParameter("userId", user.getId());
   query.setParameter("joiningDate", new Date());
   query.executeUpdate();
 }
 public static Customer findCustomerByIndexedParameter(
     EntityManager entityManager, String first, String last) {
   Query query =
       entityManager.createQuery(
           "from Customer c " + " where c.firstName=?1" + " and c.lastName=?2");
   query.setParameter(1, first);
   query.setParameter(2, last);
   return (Customer) query.getSingleResult();
 }
Exemplo n.º 10
0
 private void updateLastGroupVisit(final User user, final GroupImpl group) {
   if (group != null) {
     final Query query =
         entityManager.createNativeQuery(
             "update GROUP_USER SET LAST_VISIT=:now where GROUP_ID=:groupId and USER_ID=:userId");
     query.setParameter("now", new Date());
     query.setParameter("groupId", group.getId());
     query.setParameter("userId", user.getId());
     query.executeUpdate();
   }
 }
Exemplo n.º 11
0
 public void createTrack(
     final User user, final String title, final String points, final double length) {
   final Query query =
       entityManager.createNativeQuery(
           "INSERT INTO TRACKS SET OWNER_ID=:userId, TITLE=:title, POINTS=:points, LENGTH=:length");
   query.setParameter("userId", user.getId());
   query.setParameter("title", title);
   query.setParameter("points", points);
   query.setParameter("length", length);
   query.executeUpdate();
 }
Exemplo n.º 12
0
 public void updateMessage(
     final User user, final Long messageId, final String content, final MessageKind kind)
     throws AccessDeniedException {
   final String table = kind == MessageKind.PRIVATE ? "MESSAGES" : "PUBLIC_MESSAGES";
   final Query query =
       entityManager.createNativeQuery(
           "update " + table + " SET CONTENT=:content where ID=:id and SENDER_ID=:userId");
   query.setParameter("content", content);
   query.setParameter("id", messageId);
   query.setParameter("userId", user.getId());
   if (query.executeUpdate() != 1) throw new AccessDeniedException();
 }
Exemplo n.º 13
0
 private Double fetchGlobalDistance(final Group group) {
   final Query query =
       query(
           "select sum(w.distance) from GroupImpl g left join g.members u left join u.workouts w where g=:group");
   query.setParameter("group", group);
   return (Double) query.getSingleResult();
 }
Exemplo n.º 14
0
 private PaginatedCollection<User> fetchGroupMembers(final Group group) {
   final String queryString =
       "select u from GroupImpl g inner join g.members u where g=:group order by u.name";
   final Query query = query(queryString);
   query.setParameter("group", group);
   return paginateList(0, 100, query.getResultList());
 }
Exemplo n.º 15
0
 private Collection<GroupData> fetchGroupDataForUser(
     final User user, final boolean restrictToSuscribed) {
   final String ifConnectedColumns =
       "max(ifnull(USER_ID=:userId, false))>0, sum(ifnull(USER_ID=:userId AND LAST_VISIT<PUBLIC_MESSAGES.`DATE`, false))";
   final Query query =
       entityManager.createNativeQuery(
           "select GROUPS.ID, name, count(DISTINCT GROUP_USER.USER_ID), "
               + (user != null ? ifConnectedColumns : " 0,0")
               + " from GROUPS left join  GROUP_USER on GROUP_ID=ID "
               + " left join PUBLIC_MESSAGES on PUBLIC_MESSAGES.GROUP_ID=GROUP_USER.GROUP_ID "
               + (restrictToSuscribed ? " where GROUP_USER.USER_ID=:userId" : "")
               + " group by GROUPS.ID order by CREATION_DATE");
   if (user != null) query.setParameter("userId", user.getId());
   final List<Object[]> list = query.getResultList();
   final Collection<GroupData> result = new ArrayList<GroupData>(list.size());
   for (final Object[] o : list)
     result.add(
         new GroupData(
             ((Number) o[0]).longValue(),
             UserStringImpl.valueOf(String.valueOf(o[1])),
             ((Number) o[2]).longValue(),
             ((Number) o[3]).intValue() != 0,
             ((Number) o[4]).intValue()));
   return result;
 }
Exemplo n.º 16
0
 public void deleteMessageFor(final Long id, final User user) {
   final Query query =
       entityManager.createNativeQuery(
           "update MESSAGES SET deleted_by=:user_id where ID=:id and deleted_by IS NULL and receiver_id <> sender_id and (receiver_id=:user_id or sender_id=:user_id)");
   query.setParameter("user_id", user.getId());
   query.setParameter("id", id);
   final int updated = query.executeUpdate();
   if (updated == 0) {
     final Query query2 =
         entityManager.createNativeQuery(
             "delete from MESSAGES where ID=:id and (receiver_id=:user_id or sender_id=:user_id)");
     query2.setParameter("id", id);
     query2.setParameter("user_id", user.getId());
     query2.executeUpdate();
   }
 }
Exemplo n.º 17
0
 public List<NewMessageData> fetchNewMessagesCount(final User user) {
   final Query query =
       query(
           "select new com.nraynaud.sport.data.NewMessageData(m.sender.name, count(m)) from PrivateMessageImpl m where m.receiver = :user and m.read = false group by m.sender.name");
   query.setParameter("user", user);
   return query.getResultList();
 }
 /** Read all address. */
 public void test() throws Exception {
   EntityManager manager = createEntityManager();
   Query query = manager.createQuery("Select a from Address a where a.city = :city");
   query.setParameter("city", "Ottawa");
   List result = list(query, manager);
   manager.close();
 }
Exemplo n.º 19
0
  @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;
  }
Exemplo n.º 20
0
 @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;
 }
Exemplo n.º 21
0
 public StatisticsPageData fetchStatisticsPageData(final Long userId, final String discipline)
     throws UserNotFoundException {
   final User user = fetchUser(userId);
   final String fromWhereClause =
       " from WorkoutImpl w where :user MEMBER OF w.participants "
           + (discipline != null ? " and discipline = :discipline " : " ");
   final Query disciplineQuery =
       query(
           "select w.discipline, count(*) from WorkoutImpl w "
               + "WHERE :user MEMBER OF w.participants GROUP BY w.discipline ORDER BY count(*) DESC");
   disciplineQuery.setParameter("user", user);
   final Query query = query("select sum(w.distance) " + fromWhereClause);
   bindQuery(query, user, discipline);
   final Query query2 =
       query(
           "select year(w.date), sum(w.distance), sum(w.duration), sum(w.energy) "
               + fromWhereClause
               + " GROUP BY year(w.date) ORDER BY year(w.date) DESC");
   bindQuery(query2, user, discipline);
   final Query query3 =
       query(
           "select year(w.date), month(w.date), sum(w.distance), sum(w.duration), sum(w.energy) "
               + fromWhereClause
               + "GROUP BY year(w.date), month(w.date) "
               + "ORDER BY year(w.date)  DESC, month(w.date)  DESC");
   bindQuery(query3, user, discipline);
   return new StatisticsPageData(
       user,
       disciplineQuery.getResultList(),
       query.getSingleResult(),
       query2.getResultList(),
       query3.getResultList());
 }
Exemplo n.º 22
0
 private void separatePrivateMessagesFromWorkout(final Long id) {
   final Query query =
       entityManager.createNativeQuery(
           "UPDATE MESSAGES SET WORKOUT_ID=NULL WHERE WORKOUT_ID=:id AND RECEIVER_ID IS NOT NULL");
   query.setParameter("id", id);
   query.executeUpdate();
 }
Exemplo n.º 23
0
 private Collection<ConversationSummary> fetchCorrespondents(final User user) {
   final Map<String, ConversationSummary> correspondants =
       new HashMap<String, ConversationSummary>();
   {
     final Query query =
         query(
             "select m.sender.name, m.receiver.name, count(m), m.read from PrivateMessageImpl m where (m.receiver=:user OR "
                 + "(m.sender=:user)) AND(m.deleter IS NULL OR m.deleter <> :user) "
                 + "group by m.sender.name, m.receiver.name, m.read");
     query.setParameter("user", user);
     for (final Object[] row : (List<Object[]>) query.getResultList()) {
       final boolean sent = row[0].equals(((UserImpl) user).getBareName());
       final String name = (String) (sent ? row[1] : row[0]);
       final ConversationSummary previous = correspondants.get(name);
       final long count = ((Number) row[2]).longValue();
       final long newCount;
       if (row[3].equals(Boolean.FALSE) && !sent) newCount = count;
       else newCount = 0;
       if (previous != null) {
         correspondants.put(
             name,
             new ConversationSummary(
                 UserStringImpl.valueOf(name),
                 count + previous.messageCount,
                 newCount + previous.newMessageCount));
       } else
         correspondants.put(
             name, new ConversationSummary(UserStringImpl.valueOf(name), count, newCount));
     }
   }
   return new TreeSet<ConversationSummary>(correspondants.values());
 }
Exemplo n.º 24
0
  public Map<String, Object> findByMapWithCond(
      final Map<String, Object> params, int page, int rows, String order, boolean asc)
      throws HibernateException {
    StringBuilder hql = new StringBuilder("from " + className);
    Query query, countQuery;
    Long total;
    Map<String, Object> alterParams = new HashMap<>();
    if (null != params && !params.isEmpty()) {
      hql.append(" where ");
      for (String field : params.keySet()) {
        int i = field.indexOf(" ");
        Assert.isTrue(i != -1, "Wrong condition, must have space inside!");
        String ramdonName = "_" + Utils.getRandomString(8);
        hql.append(field).append(" :").append(ramdonName).append(" and ");
        alterParams.put(ramdonName, params.get(field));
      }
      hql.append("1=1");
      countQuery = getSession().createQuery("SELECT count(*) " + hql.toString());
      if (null != order) {
        hql.append(" order by ").append(order);
        if (asc) hql.append(" asc");
        else hql.append(" desc");
      }
      query = getSession().createQuery(hql.toString());

      for (String field : alterParams.keySet()) {
        query.setParameter(field, alterParams.get(field));
        countQuery.setParameter(field, alterParams.get(field));
      }
    } else {
      countQuery = getSession().createQuery("SELECT count(*) " + hql.toString());
      if (null != order) {
        hql.append(" order by ").append(order);
        if (asc) hql.append(" asc");
        else hql.append(" desc");
      }
      query = getSession().createQuery(hql.toString());
    }
    total = (Long) countQuery.uniqueResult();
    if (page > 0 && rows > 0) {
      query.setFirstResult((page - 1) * rows).setMaxResults(rows);
    }
    Map<String, Object> result = new HashMap<String, Object>();
    result.put("total", total);
    result.put("rows", query.list());
    return result;
  }
Exemplo n.º 25
0
 @Override
 public Collection<AbstractAanvraag> getAanvragen(Status status) {
   Query query =
       getEntityManager().createQuery("SELECT x FROM AbstractAanvraag x WHERE x.status=:status");
   query.setParameter("status", status);
   Collection<AbstractAanvraag> aanvragen = query.getResultList();
   return aanvragen;
 }
Exemplo n.º 26
0
 public TbAplicativo daTbAplicativoByFIngreso(Date fIngreso) {
   sesion = sessionFactory.openSession();
   Query query = sesion.getNamedQuery("TbAplicativo.findByFIngreso");
   query.setParameter("fIngreso", fIngreso);
   TbAplicativo tbAplicativo = (TbAplicativo) query.uniqueResult();
   sesion.close();
   return tbAplicativo;
 }
Exemplo n.º 27
0
 @Override
 public Collection<Opname> getOpnames(OpnameMethode opnameMethode) {
   Query query =
       getEntityManager().createQuery("SELECT x FROM Opname x WHERE x.methode = :methode");
   query.setParameter("methode", opnameMethode);
   Collection<Opname> opnames = query.getResultList();
   return opnames;
 }
Exemplo n.º 28
0
 @SuppressWarnings({"unchecked"})
 public List<String> fechLoginBeginningBy(final String prefix) {
   final Query query =
       query(
           "select u.name from UserImpl u where u.name<>'googlebot' AND u.name LIKE CONCAT(:prefix, '%')");
   query.setParameter("prefix", prefix);
   return query.getResultList();
 }
Exemplo n.º 29
0
 public User facebookLogin(final Long facebookId) {
   final Query query = query("select u from UserImpl u where u.facebookId=:facebookId");
   query.setParameter("facebookId", facebookId);
   try {
     return (User) query.getSingleResult();
   } catch (NoResultException e) {
     return null;
   }
 }
Exemplo n.º 30
0
 private Double fetchGlobalDistance(final User user) {
   final Query query =
       query(
           "select sum(w.distance) from WorkoutImpl w where 1=1"
               + (user != null ? " and :user MEMBER OF w.participants" : ""));
   if (user != null) query.setParameter("user", user);
   final Double result = (Double) query.getSingleResult();
   return result == null ? Double.valueOf(0) : result;
 }