org.springframework.dao.EmptyResultDataAccessException Java Examples

The following examples show how to use org.springframework.dao.EmptyResultDataAccessException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AccountDataRepository.java    From star-zone with Apache License 2.0 7 votes vote down vote up
public AccountData findByUserId(long userId) {
    final String sql = "SELECT * FROM " + TABLE_NAME + " WHERE user_id=? LIMIT 1";
    AccountData accountData = null;
    try {
        accountData = jdbcTemplate.queryForObject(sql,
                new Object[]{userId}, new int[]{Types.BIGINT}
                , new AccountDataMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }

    return accountData;
}
 
Example #2
Source File: JdbcTokenStore.java    From JwtPermission with Apache License 2.0 6 votes vote down vote up
@Override
public String[] findRolesByUserId(String userId, Token token) {
    // 判断是否自定义查询
    if (getFindRolesSql() == null || getFindRolesSql().trim().isEmpty()) {
        return token.getRoles();
    }
    try {
        List<String> roleList = jdbcTemplate.query(getFindRolesSql(), new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString(1);
            }
        }, userId);
        return JacksonUtil.stringListToArray(roleList);
    } catch (EmptyResultDataAccessException e) {
        logger.debug("JwtPermission", e.getCause());
    }
    return null;
}
 
Example #3
Source File: MailingSummaryDataSet.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getTargetIds(int mailingId, @VelocityCheck int companyId) throws Exception {
	String query = "SELECT target_expression FROM mailing_tbl WHERE mailing_id = ? AND company_id = ?";
	String targetExpression = "";
	try {
		targetExpression = select(logger, query, String.class, mailingId, companyId);
	} catch (EmptyResultDataAccessException e) {
		// nothing to do
	}
	final Pattern pattern = Pattern.compile("^.*?(\\d+)(.*)$");
	Set<Integer> targetIds = new HashSet<>();
	if (targetExpression != null) {
		Matcher matcher = pattern.matcher(targetExpression);
		while (matcher.matches()) {
			targetIds.add(Integer.parseInt(matcher.group(1)));
			targetExpression = matcher.group(2);
			matcher = pattern.matcher(targetExpression);
		}
	}
	return StringUtils.join(targetIds, ",");
}
 
Example #4
Source File: JdbcOwnerRepositoryImpl.java    From spring-graalvm-native with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the {@link Owner} with the supplied <code>id</code>; also loads the
 * {@link Pet Pets} and {@link Visit Visits} for the corresponding owner, if not
 * already loaded.
 */
@Override
public Owner findById(int id) throws DataAccessException {
    Owner owner;
    try {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        owner = this.namedParameterJdbcTemplate.queryForObject(
                "SELECT id, first_name, last_name, address, city, telephone FROM owners WHERE id= :id", params,
                BeanPropertyRowMapper.newInstance(Owner.class));
    } catch (EmptyResultDataAccessException ex) {
        throw new DataRetrievalFailureException("Cannot find Owner: " + id);
    }
    loadPetsAndVisits(owner);
    return owner;
}
 
Example #5
Source File: ManageSubscription.java    From OpenCue with Apache License 2.0 6 votes vote down vote up
@Override
public void find(SubscriptionFindRequest request, StreamObserver<SubscriptionFindResponse> responseObserver)
        throws CueGrpcException{
    String name = request.getName();
    try {
        String[] parts = name.split("\\.", 3);
        if (parts.length != 3) {
            throw new CueGrpcException("Subscription names must be in the form of alloc.show");
        }
        SubscriptionFindResponse response = SubscriptionFindResponse.newBuilder()
                .setSubscription(whiteboard.findSubscription(parts[2], parts[0] + "." + parts[1]))
                .build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    } catch (EmptyResultDataAccessException e) {
        responseObserver.onError(Status.NOT_FOUND
                .withDescription("A subscription to " + name + " was not found.")
                .withCause(e)
                .asRuntimeException());
    }
}
 
Example #6
Source File: LayerDaoJdbc.java    From OpenCue with Apache License 2.0 6 votes vote down vote up
@Override
public long findPastMaxRSS(JobInterface job, String name) {
    try {
        long maxRss = getJdbcTemplate().queryForObject(FIND_PAST_MAX_RSS,
                Long.class, job.getJobId(), name);
        if (maxRss >= Dispatcher.MEM_RESERVED_MIN) {
            return maxRss;
        }
        else {
            return Dispatcher.MEM_RESERVED_MIN;
        }
    } catch (EmptyResultDataAccessException e) {
        // Actually want to return 0 here, which means
        // there is no past history.
        return 0;
    }
}
 
Example #7
Source File: LayerDaoJdbc.java    From OpenCue with Apache License 2.0 6 votes vote down vote up
@Override
public long findPastMaxRSS(JobInterface job, String name) {
    try {
        long maxRss = getJdbcTemplate().queryForObject(FIND_PAST_MAX_RSS,
                Long.class, job.getJobId(), name);
        if (maxRss >= Dispatcher.MEM_RESERVED_MIN) {
            return maxRss;
        }
        else {
            return Dispatcher.MEM_RESERVED_MIN;
        }
    } catch (EmptyResultDataAccessException e) {
        // Actually want to return 0 here, which means
        // there is no past history.
        return 0;
    }
}
 
Example #8
Source File: ManageDepend.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public void getDepend(DependGetDependRequest request, StreamObserver<DependGetDependResponse> responseObserver) {
    try {
        responseObserver.onNext(DependGetDependResponse.newBuilder()
                .setDepend(whiteboard.getDepend(request.getId()))
                .build());
        responseObserver.onCompleted();
    } catch (EmptyResultDataAccessException e) {
        responseObserver.onError(Status.NOT_FOUND
                .withDescription(e.getMessage())
                .withCause(e)
                .asRuntimeException());
    }
}
 
Example #9
Source File: SharedReportDao.java    From poli with MIT License 5 votes vote down vote up
public SharedReport findByShareKey(String shareKey) {
    String sql = "SELECT id, share_key, report_id, report_type, user_id, created_at, expired_by "
                + "FROM p_shared_report WHERE share_key=?";
    try {
        return (SharedReport) jt.queryForObject(sql, new Object[]{ shareKey }, new SharedReportRawMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #10
Source File: DataAccessUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return a single result object from the given Collection.
 * <p>Throws an exception if 0 or more than 1 element found.
 * @param results the result Collection (can be {@code null}
 * and is also expected to contain {@code null} elements)
 * @return the single result object
 * @throws IncorrectResultSizeDataAccessException if more than one
 * element has been found in the given Collection
 * @throws EmptyResultDataAccessException if no element at all
 * has been found in the given Collection
 * @since 5.0.2
 */
@Nullable
public static <T> T nullableSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
	// This is identical to the requiredSingleResult implementation but differs in the
	// semantics of the incoming Collection (which we currently can't formally express)
	if (CollectionUtils.isEmpty(results)) {
		throw new EmptyResultDataAccessException(1);
	}
	if (results.size() > 1) {
		throw new IncorrectResultSizeDataAccessException(1, results.size());
	}
	return results.iterator().next();
}
 
Example #11
Source File: LeaderElectionDaoImpl.java    From qmq with Apache License 2.0 5 votes vote down vote up
@Override
public LeaderElectionRecord queryByName(String name) {
    try {
        return jdbcTemplate.queryForObject("select id,`name`,node,last_seen_active from leader_election where `name` = ?", (rs, rowNum) -> {
            LeaderElectionRecord record = new LeaderElectionRecord();
            record.setId(rs.getInt("id"));
            record.setName(rs.getString("name"));
            record.setNode(rs.getString("node"));
            record.setLastSeenActive(rs.getLong("last_seen_active"));
            return record;
        }, name);
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #12
Source File: HostDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public DispatchHost findDispatchHost(String name) {
    try {
        return getJdbcTemplate().queryForObject(
                GET_DISPATCH_HOST +
                "WHERE (host.str_name=? OR host.str_fqdn=?)",
                DISPATCH_HOST_MAPPER, name, name);
    } catch (EmptyResultDataAccessException e) {
        throw new EmptyResultDataAccessException(
                "Failed to find host " + name, 1);
    }
}
 
Example #13
Source File: ShowDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
public ShowEntity findShowDetail(String name) {
    try {
        return getJdbcTemplate().queryForObject(GET_SHOW + "WHERE show.str_name=?",
                SHOW_MAPPER, name);
    } catch (EmptyResultDataAccessException e) {
        return getJdbcTemplate().queryForObject(GET_SHOW_BY_ALIAS + "AND show_alias.str_name = ?",
                SHOW_MAPPER, name);
    }
}
 
Example #14
Source File: CommentRepository.java    From star-zone with Apache License 2.0 5 votes vote down vote up
public Comment findById(long id) {
    final String sql = "SELECT * FROM " + TABLE_NAME + " WHERE id=? LIMIT 1";
    Comment comment = null;
    try {
        comment = jdbcTemplate.queryForObject(sql, new Object[]{id}, new int[]{Types.BIGINT}
                , new CommentMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }

    return comment;
}
 
Example #15
Source File: UserDao.java    From poli with MIT License 5 votes vote down vote up
public User findById(long id) {
    String sql = "SELECT id, username, name, sys_role "
                + "FROM p_user WHERE id=?";
    try {
        User user = (User) jt.queryForObject(sql, new Object[]{ id }, new UserInfoRowMapper());
        return user;
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #16
Source File: ManageJob.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public void addRenderPartition(JobAddRenderPartRequest request, StreamObserver<JobAddRenderPartResponse> responseObserver) {
    setupJobData(request.getJob());
    LocalHostAssignment lha = new LocalHostAssignment();
    lha.setJobId(job.getId());
    lha.setThreads(request.getThreads());
    lha.setMaxCoreUnits(request.getMaxCores() * 100);
    lha.setMaxMemory(request.getMaxMemory());
    lha.setMaxGpu(request.getMaxGpu());
    lha.setType(RenderPartitionType.JOB_PARTITION);

    if (localBookingSupport.bookLocal(job, request.getHost(), request.getUsername(), lha)) {
        try {
            RenderPartition renderPart = whiteboard.getRenderPartition(lha);
            responseObserver.onNext(JobAddRenderPartResponse.newBuilder()
                    .setRenderPartition(renderPart)
                    .build());
            responseObserver.onCompleted();
        } catch (EmptyResultDataAccessException e) {
            responseObserver.onError(Status.INTERNAL
                    .withDescription("Failed to allocate render partition to host.")
                    .asRuntimeException());
        }
    } else {
        responseObserver.onError(Status.INTERNAL
                .withDescription("Failed to find suitable frames.")
                .asRuntimeException());
    }
}
 
Example #17
Source File: AccountDataRepository.java    From star-zone with Apache License 2.0 5 votes vote down vote up
public AccountData findByUserId(long userId) {
    final String sql = "SELECT * FROM " + TABLE_NAME + " WHERE user_id=? LIMIT 1";
    AccountData accountData = null;
    try {
        accountData = jdbcTemplate.queryForObject(sql,
                new Object[]{userId}, new int[]{Types.BIGINT}
                , new AccountDataMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }

    return accountData;
}
 
Example #18
Source File: BookingManagerTests.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
@Rollback(true)
public void removeLocalHostAssignment() {

    DispatchHost h = createHost();
    JobDetail j = launchJob();

    LocalHostAssignment lja = new LocalHostAssignment();
    lja.setMaxCoreUnits(200);
    lja.setMaxMemory(CueUtil.GB4);
    lja.setThreads(2);

    bookingManager.createLocalHostAssignment(h, j, lja);
    assertFalse(bookingManager.hasActiveLocalFrames(h));

    /*
     * Now remove the local host assignment.
     */
    bookingManager.removeLocalHostAssignment(lja);

    /*
     * Ensure its gone.
     */
    try {
        hostDao.getHost(lja);
        fail("Local host is still present but should be gone");
    } catch (EmptyResultDataAccessException e) {}

    /*
     * Ensure the cores are back on the host.
     */
    assertEquals(200, hostDao.getDispatchHost(h.getId()).idleCores);
}
 
Example #19
Source File: CaptchaRecordRepository.java    From star-zone with Apache License 2.0 5 votes vote down vote up
public CaptchaRecord findLatestByMobile(String mobile) {
    final String sql = "SELECT * FROM " + TABLE_NAME + " WHERE mobile=? " +
            " ORDER BY expire_time DESC LIMIT 1";
    CaptchaRecord captchaRecord = null;
    try {
        captchaRecord = jdbcTemplate.queryForObject(sql, new Object[] {mobile},
                new int[] {Types.VARCHAR },
                new CaptchaRecordMapper());
    } catch (EmptyResultDataAccessException e){
        captchaRecord = null;
    }

    return captchaRecord;
}
 
Example #20
Source File: UserDao.java    From poli with MIT License 5 votes vote down vote up
public User findByApiKey(String apiKey) {
    String sql = "SELECT id, username, name, sys_role, session_key "
                + "FROM p_user WHERE api_key=?";
    try {
        User user = (User) jt.queryForObject(sql, new Object[]{ apiKey }, new UserSesssionKeyMapper());
        return user;
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #21
Source File: UserScoreRepository.java    From star-zone with Apache License 2.0 5 votes vote down vote up
public UserScore findOne(long userId) {
    String sql = " SELECT * FROM " + TABLE_NAME + " WHERE user_id=:userId ";
    Map<String, Object> parameter = new HashMap<String, Object>();
    parameter.put("userId", userId);
    UserScore userScore = null;

    try {
        userScore = namedParameterJdbcTemplate.queryForObject(sql, parameter,
                new BeanPropertyRowMapper<>(UserScore.class));
    } catch (EmptyResultDataAccessException e) {
        userScore = null;
    }
    return userScore;
}
 
Example #22
Source File: DailyCheckInRepository.java    From star-zone with Apache License 2.0 5 votes vote down vote up
public Date getLatestTime(long userId) {
    String sql = "SELECT MAX(create_time) FROM " + TABLE_NAME + " WHERE user_id=? ";
    Date date = null;

    try {
        date = jdbcTemplate.queryForObject(sql, new Object[]{userId}, new int[]{Types.BIGINT},
                Date.class);
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
    return date;
}
 
Example #23
Source File: UserDao.java    From poli with MIT License 5 votes vote down vote up
public User findByUsernameAndPassword(String username, String rawPassword) {
    String encryptedPassword = PasswordUtils.getMd5Hash(rawPassword);
    String sql = "SELECT id, username, name, sys_role "
                + "FROM p_user "
                + "WHERE username=? AND password=?";
    try {
        User user = (User) jt.queryForObject(sql, new Object[]{username, encryptedPassword}, new UserInfoRowMapper());
        return user;
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #24
Source File: ManageFacility.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public void get(FacilityGetRequest request, StreamObserver<FacilityGetResponse> responseObserver) {
    try {
        FacilityGetResponse response = FacilityGetResponse.newBuilder()
                .setFacility(whiteboard.getFacility(request.getName()))
                .build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    } catch (EmptyResultDataAccessException e) {
        responseObserver.onError(Status.NOT_FOUND
                .withDescription(e.getMessage())
                .withCause(e)
                .asRuntimeException());
    }
}
 
Example #25
Source File: GroupDao.java    From poli with MIT License 5 votes vote down vote up
public Group findById(long groupId) {
    String sql = "SELECT id, name FROM p_group WHERE id=?";
    try {
        return (Group) jt.queryForObject(sql, new Object[]{ groupId }, new GroupRowMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #26
Source File: RatingRepository.java    From Microservices-with-Spring-Cloud with MIT License 5 votes vote down vote up
public RatingResult calculateRating(String type, String entityId) {
    try {
        return jdbcTemplate.queryForObject("select  type, entity_id as entityId," +
                        " avg(rating) as rating, count(*) as ratingCount" +
                        " from ratings" +
                        " where type=:type and entity_id=:entity_id" +
                        " group by type, entity_id",
                new MapSqlParameterSource()
                        .addValue("type", type)
                        .addValue("entity_id", entityId),
                new BeanPropertyRowMapper<>(RatingResult.class));
    } catch (EmptyResultDataAccessException ex) {
        return new RatingResult(type, entityId, BigDecimal.ZERO, 0);
    }
}
 
Example #27
Source File: MailingSummaryDataSet.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getTempTableValuesByCategoryAndTargetGroupId(int tempTableID, String category, int targetGroupId) throws Exception {
	String query = "SELECT value FROM " + getTempTableName(tempTableID) + " WHERE category = ? AND targetgroup_id = ?";
       int value = 0;
       try {
           value = selectEmbedded(logger, query, Integer.class, category, targetGroupId);
       }
       catch (EmptyResultDataAccessException e) {
           logger.error("No data found for category: " + category + ", targetId: " + targetGroupId);
       }
	return value;
}
 
Example #28
Source File: TotalOptimizationDataSet.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getTempTableValuesByCategoryAndMailingId(int tempTableID, String category, int mailingId) throws Exception {
	String query = "SELECT value FROM tmp_report_aggregation_" + tempTableID + "_tbl WHERE category = ? AND mailing_id = ?";
       int value = 0;
       try {
           value = selectEmbedded(logger, query, Integer.class, category, mailingId);
       }
       catch (EmptyResultDataAccessException e) {
           logger.error("No data found for category: " + category + ", mailingId: " + mailingId);
       }
	return value;
}
 
Example #29
Source File: JdbcPetRepositoryImpl.java    From spring-graalvm-native with Apache License 2.0 5 votes vote down vote up
@Override
public Pet findById(int id) throws DataAccessException {
    Integer ownerId;
    try {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        ownerId = this.namedParameterJdbcTemplate.queryForObject("SELECT owner_id FROM pets WHERE id=:id", params,
                Integer.class);
    } catch (EmptyResultDataAccessException ex) {
        throw new DataRetrievalFailureException("Cannot find Pet: " + id);
    }
    Owner owner = this.ownerRepository.findById(ownerId);
    return EntityUtils.getById(owner.getPets(), Pet.class, id);
}
 
Example #30
Source File: Runner.java    From spring-graalvm-native with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public void run(String... args) throws Exception {
	Assert.isTrue(TransactionSynchronizationManager.isActualTransactionActive(), "Expected transaction");
	try {
		find(1L);
	}
	catch (EmptyResultDataAccessException e) {
		entities.update(ADD_FOO, 1L, "Hello");
	}
}