Java 类org.springframework.dao.support.DataAccessUtils 实例源码

项目:dhus-core    文件:UserDao.java   
public User getByName (final String name)
{
   User user = (User)DataAccessUtils.uniqueResult (
      getHibernateTemplate ().find (
      "From User u where u.username=?", name));   

   // Optimization user extraction: most of the users uses case-sensitive
   // match for the login. A Requirement of the project asked for non-case
   // sensitive match. The extraction of non-case sensitive login from
   // database requires conversions and forbid the usage of indexes, so it
   // is much more slow.
   // This Fix aims to first try the extraction of the user with exact match
   // equals operator, then if not match use the toLower conversion.
   if (user==null)
      user = (User)DataAccessUtils.uniqueResult (
         getHibernateTemplate ().find (
         "From User u where lower(u.username)=lower(?)", name));
   return user;
}
项目:dhus-core    文件:CollectionDao.java   
/**
 * Counts collections whose the given user is authorized.
 * @param user the given user.
 * @return number of authorized collection for user.
 */
public int count (User user)
{
   String userString = "";
   // Bypass for Data Right Managers. They can see all products and
   // collections.
   if ( !cfgManager.isDataPublic () && (user != null) &&
      !user.getRoles ().contains (Role.DATA_MANAGER))
   {
      userString =
         "WHERE ('" + user.getUUID () + "' in elements(authorizedUsers) OR '" +
                  userDao.getPublicData ().getUUID () +
                  "' in elements(authorizedUsers))";
   }

   return DataAccessUtils
      .intResult (find ("select count(*) FROM Collection " + userString));
}
项目:dhus-core    文件:HibernateDao.java   
@SuppressWarnings ("rawtypes")
private int countOpenSessions ()
{
   return DataAccessUtils.intResult (getHibernateTemplate ().execute (
      new HibernateCallback<List>()
      {
         @Override
         public List doInHibernate(Session session) 
            throws HibernateException, SQLException
         {
            String sql = 
               "SELECT count (*) FROM INFORMATION_SCHEMA.SYSTEM_SESSIONS";
            SQLQuery query = session.createSQLQuery (sql);
            return query.list ();
         }
      }));
}
项目:dhus-core    文件:HibernateDao.java   
@SuppressWarnings ({ "unchecked", "rawtypes" })
private String getSystemByName (final String name, final int index)
{
   return DataAccessUtils.uniqueResult (getHibernateTemplate ().execute (
      new HibernateCallback<List>()
      {
         @Override
         public List doInHibernate(Session session) 
            throws HibernateException, SQLException
         {
            String sql = 
               "SELECT " + name +
               " FROM INFORMATION_SCHEMA.SYSTEM_SESSIONS" +
               " LIMIT  1 OFFSET " + index;
            SQLQuery query = session.createSQLQuery (sql);
            return query.list ();
         }
      })).toString ();
}
项目:dhus-core    文件:ProductDao.java   
/**
 * Returns the number of Product records whose `processed` field is `true`.
 * @param filter an optional additionnal `where` clause (without the "where" token).
 * @param collection_uuid an optional parent collection ID.
 * @return a number of rows in table `PRODUCTS`.
 */
public int count (String filter, final String collection_uuid)
{
   StringBuilder sb = new StringBuilder("select count(*) ");
   if (collection_uuid != null)
   {
         sb.append("from Collection c left outer join c.products p ");
         sb.append("where c.uuid='").append(collection_uuid).append("' and ");
   }
   else
   {
      sb.append("from Product p where ");
   }
   sb.append("p.processed=true");

   if (filter != null && !filter.isEmpty())
   {
      sb.append(" and ").append(filter);
   }

   return DataAccessUtils.intResult(find(sb.toString()));
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:DataSourceHealthIndicator.java   
private void doDataSourceHealthCheck(Health.Builder builder) throws Exception {
    String product = getProduct();
    builder.up().withDetail("database", product);
    String validationQuery = getValidationQuery(product);
    if (StringUtils.hasText(validationQuery)) {
        try {
            // Avoid calling getObject as it breaks MySQL on Java 7
            List<Object> results = this.jdbcTemplate.query(validationQuery,
                    new SingleColumnRowMapper());
            Object result = DataAccessUtils.requiredSingleResult(results);
            builder.withDetail("hello", result);
        }
        catch (Exception ex) {
            builder.down(ex);
        }
    }
}
项目:rabbitframework    文件:DefaultSqlDataAccess.java   
@SuppressWarnings("unchecked")
public <K, V> Map<K, V> selectMap(String statement, Object parameter,
                                  String mapKey, RowBounds rowBounds) {
    final List<?> list = selectList(statement, parameter, rowBounds);
    if (list == null || list.size() == 0) {
        return new HashMap<K, V>();
    }
    if (mapKey == null) {
        return (Map<K, V>) DataAccessUtils.requiredSingleResult(list);
    }
    ObjectFactory objectFactory = configuration.getObjectFactory();
    Map<K, V> selectedMap = objectFactory.create(Map.class);
    for (Object o : list) {
        V value = (V) o;
        MetaObject mo = MetaObject.forObject(o, objectFactory);
        final K key = (K) mo.getValue(mapKey);
        selectedMap.put(key, value);
    }
    return selectedMap;
}
项目:spring-boot-concourse    文件:DataSourceHealthIndicator.java   
private void doDataSourceHealthCheck(Health.Builder builder) throws Exception {
    String product = getProduct();
    builder.up().withDetail("database", product);
    String validationQuery = getValidationQuery(product);
    if (StringUtils.hasText(validationQuery)) {
        try {
            // Avoid calling getObject as it breaks MySQL on Java 7
            List<Object> results = this.jdbcTemplate.query(validationQuery,
                    new SingleColumnRowMapper());
            Object result = DataAccessUtils.requiredSingleResult(results);
            builder.withDetail("hello", result);
        }
        catch (Exception ex) {
            builder.down(ex);
        }
    }
}
项目:ResBill    文件:DailyUsageDAOImpl.java   
/**
 * Najde posledni zname vyuziti zdroju serveru
 * 
 * @return
 */
@Override
public DailyUsage findServerLastDailyUsage(Integer serverId) {
  StringBuilder jpql = new StringBuilder();
  jpql.append(" SELECT dailyUsage ");
  jpql.append(" FROM DailyUsage AS dailyUsage ");
  jpql.append(" JOIN dailyUsage.dailyImport AS dailyImport ");
  jpql.append(" WHERE dailyUsage.server.id = :serverId ");
  jpql.append(" ORDER BY dailyImport.date DESC ");

  TypedQuery<DailyUsage> query = em.createQuery(jpql.toString(), DailyUsage.class);
  query.setMaxResults(1);
  query.setParameter("serverId", serverId);

  return DataAccessUtils.uniqueResult(query.getResultList());
}
项目:ResBill    文件:TransactionDAOImpl.java   
/**
 * Pro pozadovany kontrakt najde nejblizsi volne poradove cislo trasnakce v ramci tohoto kontraktu
 */
@Override
public Integer getNextOrder(Integer contractId) {
    StringBuilder jpql = new StringBuilder();
    jpql.append(" SELECT MAX(transaction.order) ");
    jpql.append(" FROM Transaction AS transaction ");
    jpql.append(" JOIN transaction.contract AS contract ");
    jpql.append(" WHERE contract.id = :contractId ");

    TypedQuery<Integer> query = em.createQuery(jpql.toString(), Integer.class);

    query.setParameter("contractId", contractId);

    Integer maxOrder = DataAccessUtils.uniqueResult(query.getResultList());
    if (maxOrder == null) {
        maxOrder = 0;
    }

    return maxOrder + 1;
}
项目:contestparser    文件:DataSourceHealthIndicator.java   
private void doDataSourceHealthCheck(Health.Builder builder) throws Exception {
    String product = getProduct();
    builder.up().withDetail("database", product);
    String validationQuery = getValidationQuery(product);
    if (StringUtils.hasText(validationQuery)) {
        try {
            // Avoid calling getObject as it breaks MySQL on Java 7
            List<Object> results = this.jdbcTemplate.query(validationQuery,
                    new SingleColumnRowMapper());
            Object result = DataAccessUtils.requiredSingleResult(results);
            builder.withDetail("hello", result);
        }
        catch (Exception ex) {
            builder.down(ex);
        }
    }
}
项目:DataHubSystem    文件:UserDao.java   
public User getByName (final String name)
{
   User user = (User)DataAccessUtils.uniqueResult (
      getHibernateTemplate ().find (
      "From User u where u.username=?", name));   

   // Optimization user extraction: most of the users uses case-sensitive
   // match for the login. A Requirement of the project asked for non-case
   // sensitive match. The extraction of non-case sensitive login from
   // database requires conversions and forbid the usage of indexes, so it
   // is much more slow.
   // This Fix aims to first try the extraction of the user with exact match
   // equals operator, then if not match use the toLower conversion.
   if (user==null)
      user = (User)DataAccessUtils.uniqueResult (
         getHibernateTemplate ().find (
         "From User u where lower(u.username)=lower(?)", name));
   return user;
}
项目:DataHubSystem    文件:CollectionDao.java   
/**
 * Counts collections whose the given user is authorized.
 * @param user the given user.
 * @return number of authorized collection for user.
 */
public int count (User user)
{
   String userString = "";
   // Bypass for Data Right Managers. They can see all products and
   // collections.
   if ( !cfgManager.isDataPublic () && (user != null) &&
      !user.getRoles ().contains (Role.DATA_MANAGER))
   {
      userString =
         "WHERE ('" + user.getUUID () + "' in elements(authorizedUsers) OR '" +
                  userDao.getPublicData ().getUUID () +
                  "' in elements(authorizedUsers))";
   }

   return DataAccessUtils
      .intResult (find ("select count(*) FROM Collection " + userString));
}
项目:DataHubSystem    文件:HibernateDao.java   
@SuppressWarnings ("rawtypes")
private int countOpenSessions ()
{
   return DataAccessUtils.intResult (getHibernateTemplate ().execute (
      new HibernateCallback<List>()
      {
         @Override
         public List doInHibernate(Session session) 
            throws HibernateException, SQLException
         {
            String sql = 
               "SELECT count (*) FROM INFORMATION_SCHEMA.SYSTEM_SESSIONS";
            SQLQuery query = session.createSQLQuery (sql);
            return query.list ();
         }
      }));
}
项目:DataHubSystem    文件:HibernateDao.java   
@SuppressWarnings ({ "unchecked", "rawtypes" })
private String getSystemByName (final String name, final int index)
{
   return DataAccessUtils.uniqueResult (getHibernateTemplate ().execute (
      new HibernateCallback<List>()
      {
         @Override
         public List doInHibernate(Session session) 
            throws HibernateException, SQLException
         {
            String sql = 
               "SELECT " + name +
               " FROM INFORMATION_SCHEMA.SYSTEM_SESSIONS" +
               " LIMIT  1 OFFSET " + index;
            SQLQuery query = session.createSQLQuery (sql);
            return query.list ();
         }
      })).toString ();
}
项目:DataHubSystem    文件:ProductDao.java   
/**
 * Returns the number of Product records whose `processed` field is `true`.
 * @param filter an optional additionnal `where` clause (without the "where" token).
 * @param collection_uuid an optional parent collection ID.
 * @return a number of rows in table `PRODUCTS`.
 */
public int count (String filter, final String collection_uuid)
{
   StringBuilder sb = new StringBuilder("select count(*) ");
   if (collection_uuid != null)
   {
         sb.append("from Collection c left outer join c.products p ");
         sb.append("where c.uuid='").append(collection_uuid).append("' and ");
   }
   else
   {
      sb.append("from Product p where ");
   }
   sb.append("p.processed=true");

   if (filter != null && !filter.isEmpty())
   {
      sb.append(" and ").append(filter);
   }

   return DataAccessUtils.intResult(find(sb.toString()));
}
项目:SIRME    文件:UsersDaoImpl.java   
public UserData getByCodeUserLoadAllData(String codeUser) {

        MyLogger.info(log, CLASS_NAME, "getByCodeUserLoadAllData", "codeUser="+codeUser, "START");

        Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession()
                .createCriteria(UserData.class, "user")
                .add( Restrictions.eq("user.codeUser", codeUser) )
                .createAlias("user.profiles", "profile", Criteria.LEFT_JOIN)
                .createAlias("user.roles", "role", Criteria.LEFT_JOIN)
                .createAlias("role.permissions", "permission", Criteria.LEFT_JOIN)
                .setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY );

        UserData data = (UserData) DataAccessUtils.uniqueResult( criteria.list() );

        MyLogger.info(log, CLASS_NAME, "getByCodeUser", "codeUser="+codeUser, "END");
        return data;

    }
项目:exchange-ws-client    文件:AbstractIntegrationTest.java   
public void getPrimaryCalendarFolder() {
    initializeCredentials();
    GetFolder request = requestFactory.constructGetFolderByName(DistinguishedFolderIdNameType.CALENDAR);
    assertNotNull(request);

    GetFolderResponse response = ewsClient.getFolder(request);
    assertNotNull(response);

    Set<BaseFolderType> results = responseUtils.parseGetFolderResponse(response);
    assertNotNull(results);

    assertFalse(CollectionUtils.isEmpty(results));
    assertEquals(1, results.size());
    BaseFolderType singleResult = DataAccessUtils.singleResult(results);
    assertNotNull(singleResult);
    assertEquals("Calendar", singleResult.getDisplayName());
}
项目:dhus-core    文件:UserDao.java   
public int countNotDeleted (String filter)
{
   return DataAccessUtils.intResult (find (
      "select count(*) FROM " + entityClass.getName () +
         " u WHERE u.deleted is false AND u.username LIKE '%" + filter +
         "%' and " + "not u.username='" +
         cfgManager.getAdministratorConfiguration ().getName () + "'" +
         " and not u.username LIKE '"+getPublicData ().getUsername ()+"' "));
}
项目:dhus-core    文件:UserDao.java   
public int countForDataRight (String filter)
{
   return DataAccessUtils.intResult (find (
      "select count(*) FROM " + entityClass.getName () +
         " u WHERE u.deleted is false AND u.username LIKE '%" + filter +
         "%' and " + "not u.username='" +
         cfgManager.getAdministratorConfiguration ().getName () + "' "));
}
项目:dhus-core    文件:UserDao.java   
public int countAll (String filter)
{
   return DataAccessUtils.intResult (find (
      "select count(*) FROM " + entityClass.getName () +
         " u WHERE u.username LIKE '%" + filter + "%'" +
         " and not u.username LIKE '" + getPublicData ().getUsername () +
         "' " ));
}
项目:dhus-core    文件:UserDao.java   
public int countNotDeletedByFilter (String filter)
{
   return DataAccessUtils.intResult (find (
      "select count(*) FROM " + entityClass.getName () +
         " u WHERE u.deleted is false AND (u.username LIKE '%" + filter +
      "%'  OR lower(u.firstname) LIKE '%"+filter.toLowerCase()+ "%'  OR lower(u.lastname) LIKE '%"+filter.toLowerCase()+
      "%'  OR lower(u.email) LIKE '%"+filter.toLowerCase()+ "%') and not u.username='" +
         cfgManager.getAdministratorConfiguration ().getName () + "'" +
         " and not u.username LIKE '"+getPublicData ().getUsername ()+"' "));
}
项目:dhus-core    文件:FileScannerDao.java   
/**
 * Retrieve the owner user of a file scanner.
 * @param fs the scanner to retrieve the user. 
 * @return the owner.
 */
public User getUserFromScanner (FileScanner fs)
{
   return (User)DataAccessUtils.uniqueResult (getHibernateTemplate ().find (
      "select u from User u where ? in elements(u.preferences.fileScanners)",
      fs));
}
项目:dhus-core    文件:ProductDao.java   
public Product getProductByPath (final URL path)
{
   if (path == null)
      return null;

   Product p = (Product)DataAccessUtils.uniqueResult(getHibernateTemplate().
      find("from Product where path=? AND processed=true",path));

   return p;
}
项目:dhus-core    文件:ProductDao.java   
/**
 * Does the product corresponding to the given url exist in the database ?
 * Processed or not.
 */
public boolean exists (URL url)
{
   if (url == null)
      return false;

   Product p = (Product)DataAccessUtils.uniqueResult(getHibernateTemplate().
      find("from Product where path=?", url));

   return p != null;
}
项目:lams    文件:JdbcTemplate.java   
@Override
public <T> T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper)
        throws DataAccessException {

    List<T> results = query(sql, args, argTypes, new RowMapperResultSetExtractor<T>(rowMapper, 1));
    return DataAccessUtils.requiredSingleResult(results);
}
项目:lams    文件:NamedParameterJdbcTemplate.java   
@Override
public <T> T queryForObject(String sql, SqlParameterSource paramSource, RowMapper<T> rowMapper)
        throws DataAccessException {

    List<T> results = getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rowMapper);
    return DataAccessUtils.requiredSingleResult(results);
}
项目:lams    文件:JpaTransactionManager.java   
@Override
public void flush() {
    try {
        this.entityManagerHolder.getEntityManager().flush();
    }
    catch (RuntimeException ex) {
        throw DataAccessUtils.translateIfNecessary(ex, getJpaDialect());
    }
}
项目:spring-jdbc-orm    文件:SupportJdbcRepository.java   
public X uniqueResult() {

            if (isCount) {
                return jdbcTemplate.queryForObject(SQLTools.getCountSQL(sql), paras, null == resultClass ? (Class<X>) Long.class : resultClass);
            }
            if (!sql.toUpperCase().contains(" LIMIT ")) {
                sql += " limit 1";
            }
            return DataAccessUtils.singleResult(list());
        }
项目:spring4-understanding    文件:JpaTransactionManager.java   
@Override
public void flush() {
    try {
        this.entityManagerHolder.getEntityManager().flush();
    }
    catch (RuntimeException ex) {
        throw DataAccessUtils.translateIfNecessary(ex, getJpaDialect());
    }
}
项目:spring4-understanding    文件:JdbcTemplate.java   
@Override
public <T> T queryForObject(String sql, Object[] args, int[] argTypes, RowMapper<T> rowMapper)
        throws DataAccessException {

    List<T> results = query(sql, args, argTypes, new RowMapperResultSetExtractor<T>(rowMapper, 1));
    return DataAccessUtils.requiredSingleResult(results);
}
项目:spring4-understanding    文件:NamedParameterJdbcTemplate.java   
@Override
public <T> T queryForObject(String sql, SqlParameterSource paramSource, RowMapper<T> rowMapper)
        throws DataAccessException {

    List<T> results = getJdbcOperations().query(getPreparedStatementCreator(sql, paramSource), rowMapper);
    return DataAccessUtils.requiredSingleResult(results);
}
项目:communote-server    文件:GroupDaoImpl.java   
/**
 * {@inheritDoc}
 */
@Override
protected int handleCount(String filter) {
    if (StringUtils.isNotBlank(filter)) {
        Criteria criteria = getSession().createCriteria(Group.class);
        criteria.add(Restrictions.ilike(GroupConstants.NAME, "%" + filter + "%"));
        criteria.add(Restrictions.ilike(GroupConstants.ALIAS, "%" + filter + "%"));
        criteria.setProjection(Projections.rowCount());
        Object result = criteria.uniqueResult();
        return Integer.parseInt(result.toString());
    }
    return DataAccessUtils.intResult(getHibernateTemplate().find(
            "select count(*) from " + GroupConstants.CLASS_NAME));
}
项目:communote-server    文件:GroupDaoImpl.java   
/**
 * {@inheritDoc}
 */
@Override
protected int handleCountMembers(long groupId) {
    Group group = load(groupId);
    if (group != null) {
        return DataAccessUtils.intResult(getHibernateTemplate().find(
                "select count(*) " + MEMBERSHIP_QUERY, groupId));
    }
    return 0;
}
项目:communote-server    文件:UserDaoImpl.java   
/**
 * {@inheritDoc}
 */
@Override
public long getActiveUserCount() {
    // Count active users, but ignore system users.
    long result = DataAccessUtils.longResult(getHibernateTemplate().find(
            "select count(*) from " + UserConstants.CLASS_NAME + " u1 where u1."
                    + UserConstants.STATUS + " = ? AND u1.id not in (SELECT u2.id FROM "
                    + UserConstants.CLASS_NAME + " u2 JOIN u2." + UserConstants.USERAUTHORITIES
                    + " auth WHERE auth." + UserAuthorityConstants.ROLE + " = ?)",
            UserStatus.ACTIVE.getValue(), UserRole.ROLE_SYSTEM_USER));
    return result;
}
项目:bamboobsc    文件:BaseDAO.java   
@Override
public int count(String hql, Object... args) throws Exception {
    Query query=this.getCurrentSession().createQuery(hql);
    for (int position=0; args!=null && position<args.length; position++) {
        this.setQueryParams(query, Integer.toString(position), args[position]);
    }
    return DataAccessUtils.intResult(query.list());
}
项目:bamboobsc    文件:BaseDAO.java   
@SuppressWarnings("unchecked")
public int countByPK(PK pk) throws Exception {
    return DataAccessUtils.intResult(
            this.getCurrentSession().createQuery(
                    " select count(*) from "+this.getPersisentName() + 
                    " where " + BaseEntityUtil.getPKOneName((BaseEntity<PK>)entityClass.newInstance()) + "=?0 ")
                    .setString("0", (String)pk).list());        
}
项目:bamboobsc    文件:BaseDAO.java   
public int countByPK(Map<String, Object> pkMap) throws Exception {
    if (pkMap==null || pkMap.size()<1) {
        return 0;
    }       
    Query query=this.getQueryByKeyMap("select count(*)", pkMap);
    return DataAccessUtils.intResult(query.list());     
}
项目:bamboobsc    文件:BaseDAO.java   
public int countByEntityUK(Map<String, Object> ukMap) throws Exception {
    if (ukMap==null || ukMap.size()<1) {
        return 0;
    }       
    Query query=this.getQueryByKeyMap("select count(*)", ukMap);
    return DataAccessUtils.intResult(query.list());
}
项目:bamboobsc    文件:BaseDAO.java   
@Override
public int count(String hql, Object... args) throws Exception {
    Query query=this.getCurrentSession().createQuery(hql);
    for (int position=0; args!=null && position<args.length; position++) {
        this.setQueryParams(query, Integer.toString(position), args[position]);
    }
    return DataAccessUtils.intResult(query.list());
}