Java Code Examples for org.springframework.dao.EmptyResultDataAccessException

The following examples show how to use org.springframework.dao.EmptyResultDataAccessException. These examples are extracted from open source projects. 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 Project: star-zone   Source File: AccountDataRepository.java    License: Apache License 2.0 6 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 Project: JwtPermission   Source File: JdbcTokenStore.java    License: 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
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
/**
 * 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 Project: OpenCue   Source File: ManageSubscription.java    License: 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 Project: OpenCue   Source File: LayerDaoJdbc.java    License: 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 Project: OpenCue   Source File: LayerDaoJdbc.java    License: 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 Project: OpenCue   Source File: ManageDepend.java    License: 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 Project: poli   Source File: SharedReportDao.java    License: 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 Project: spring-analysis-note   Source File: DataAccessUtils.java    License: 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 Project: qmq   Source File: LeaderElectionDaoImpl.java    License: 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 Project: OpenCue   Source File: HostDaoJdbc.java    License: 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 Project: OpenCue   Source File: ShowDaoJdbc.java    License: 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 Project: star-zone   Source File: CommentRepository.java    License: 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 Project: poli   Source File: UserDao.java    License: 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 Project: OpenCue   Source File: ManageJob.java    License: 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 Project: star-zone   Source File: AccountDataRepository.java    License: 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 Project: OpenCue   Source File: BookingManagerTests.java    License: 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 Project: star-zone   Source File: CaptchaRecordRepository.java    License: 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 Project: poli   Source File: UserDao.java    License: 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 Project: star-zone   Source File: UserScoreRepository.java    License: 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 Project: star-zone   Source File: DailyCheckInRepository.java    License: 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 Project: poli   Source File: UserDao.java    License: 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 Project: OpenCue   Source File: ManageFacility.java    License: 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 Project: poli   Source File: GroupDao.java    License: 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 Project: Microservices-with-Spring-Cloud   Source File: RatingRepository.java    License: 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
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
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
@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 Project: spring-graalvm-native   Source File: Runner.java    License: 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");
	}
}