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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: OrderApiController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@DeleteMapping("/{orderId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteOrder(@PathVariable("orderId") Long orderId) {
  try {
    repo.deleteById(orderId);
  } catch (EmptyResultDataAccessException e) {}
}
 
Example #9
Source File: HostDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public int getStrandedCoreUnits(HostInterface h) {
    try {
        int idle_cores =  getJdbcTemplate().queryForObject(
                "SELECT int_cores_idle FROM host WHERE pk_host = ? AND int_mem_idle <= ?",
                Integer.class, h.getHostId(),
                Dispatcher.MEM_STRANDED_THRESHHOLD);
        return (int) (Math.floor(idle_cores / 100.0)) * 100;
    } catch (EmptyResultDataAccessException e) {
        return 0;
    }
}
 
Example #10
Source File: OrderApiController.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@DeleteMapping("/{orderId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteOrder(@PathVariable("orderId") Long orderId) {
  try {
    repo.deleteById(orderId);
  } catch (EmptyResultDataAccessException e) {}
}
 
Example #11
Source File: LayerDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public LayerInterface findLayer(JobInterface job, String name) {
    try {
        return getJdbcTemplate().queryForObject(
                GET_LAYER + " AND layer.pk_job=? AND layer.str_name=?",
                LAYER_MAPPER, job.getJobId(), name);
    } catch (org.springframework.dao.EmptyResultDataAccessException e) {
        throw new EmptyResultDataAccessException("The layer " +
                name + " was not found in " + job.getName() + e, 0);
    }
}
 
Example #12
Source File: TokenDAOImpl.java    From star-zone with Apache License 2.0 5 votes vote down vote up
@Override
public String getToken(long userId) {
    final String sql = "SELECT token FROM " + TABLE_NAME + " WHERE user_id=:userId LIMIT 1";
    Map<String, Object> param = new HashMap<String, Object>();
    param.put("userId", userId);
    String token = null;
    try {
        token = namedParameterJdbcTemplate.queryForObject(sql, param, String.class);
    } catch (EmptyResultDataAccessException e) {
        token = null;
    }

    return token;
}
 
Example #13
Source File: ReportDao.java    From poli with MIT License 5 votes vote down vote up
public Report findByName(String name) {
    String sql = "SELECT id, name, style, project FROM p_report WHERE name=?";
    try {
        return (Report) jt.queryForObject(sql, new Object[]{ name }, new ReportRowMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #14
Source File: ManageFrame.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public void findFrame(FrameFindFrameRequest request, StreamObserver<FrameFindFrameResponse> responseObserver) {
    try {
        responseObserver.onNext(FrameFindFrameResponse.newBuilder()
                .setFrame(whiteboard.findFrame(request.getJob(), request.getLayer(), request.getFrame()))
                .build());
        responseObserver.onCompleted();
    } catch (EmptyResultDataAccessException e) {
        responseObserver.onError(Status.NOT_FOUND
                .withDescription(e.getMessage())
                .withCause(e)
                .asRuntimeException());
    }
}
 
Example #15
Source File: MomentRepository.java    From star-zone with Apache License 2.0 5 votes vote down vote up
public Moment findById(long id) {
    final String sql = "SELECT * FROM " + TABLE_NAME + " WHERE id=? LIMIT 1";
    Moment moment = null;
    try {
        moment = jdbcTemplate.queryForObject(sql, new Object[]{id}, new int[]{Types.BIGINT}
                , new MomentMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }

    return moment;
}
 
Example #16
Source File: ManageJob.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public void getJob(JobGetJobRequest request, StreamObserver<JobGetJobResponse> responseObserver) {
    try {
        responseObserver.onNext(JobGetJobResponse.newBuilder()
                .setJob(whiteboard.getJob(request.getId()))
                .build());
        responseObserver.onCompleted();
    } catch (EmptyResultDataAccessException e) {
        responseObserver.onError(Status.NOT_FOUND
                .withDescription(e.getMessage())
                .withCause(e)
                .asRuntimeException());
    }
}
 
Example #17
Source File: UserDaoImpl.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public Integer count() {
    try {
        return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM user", Integer.class);
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #18
Source File: HostDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public int getStrandedCoreUnits(HostInterface h) {
    try {
        int idle_cores =  getJdbcTemplate().queryForObject(
                "SELECT int_cores_idle FROM host WHERE pk_host = ? AND int_mem_idle <= ?",
                Integer.class, h.getHostId(),
                Dispatcher.MEM_STRANDED_THRESHHOLD);
        return (int) (Math.floor(idle_cores / 100.0)) * 100;
    } catch (EmptyResultDataAccessException e) {
        return 0;
    }
}
 
Example #19
Source File: SubscriptionDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
public boolean isShowOverSize(VirtualProc proc) {
    try {
        return getJdbcTemplate().queryForObject(IS_SHOW_OVER_SIZE,
                Integer.class, proc.getShowId(), proc.getAllocationId()) > 0;
    } catch (EmptyResultDataAccessException e) {
        return false;
    }
}
 
Example #20
Source File: CatalogueDatabase.java    From library with MIT License 5 votes vote down vote up
Option<Book> findBy(ISBN isbn) {
    try {
        return Option.of(
                jdbcTemplate.queryForObject(
                        "SELECT b.* FROM catalogue_book b WHERE b.isbn = ?",
                        new BeanPropertyRowMapper<>(BookDatabaseRow.class),
                        isbn.getIsbn())
                        .toBook());
    } catch (EmptyResultDataAccessException e) {
        return Option.none();

    }
}
 
Example #21
Source File: MomentLikeRepository.java    From star-zone with Apache License 2.0 5 votes vote down vote up
public MomentLike findExist(long momentId, long userId) {
    String tableName = getTableName(momentId);
    final String sql = "SELECT * FROM " + tableName + " WHERE moment_id=? " +
            " AND like_user_id=? LIMIT 1";
    MomentLike momentLike = null;
    try {
        momentLike = jdbcTemplate.queryForObject(sql, new Object[]{momentId, userId}
                , new int[]{Types.BIGINT, Types.BIGINT}
                , new MomentLikeMapper());
    } catch (EmptyResultDataAccessException e) {
        return null;
    }

    return momentLike;
}
 
Example #22
Source File: FileTemplateServiceImpl.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public Optional<TemplateInfo> getTemplateInfoWithoutConvert(String group, String template) {
    try {
        return Optional.ofNullable(templateDao.selectTemplateInfo(group, template));
    } catch (EmptyResultDataAccessException ignore) {
        return Optional.empty();
    }
}
 
Example #23
Source File: FileTemplateServiceImpl.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public Optional<TemplateInfo> getTemplateInfo(String group, String template) {
    try {
        TemplateInfo templateInfo = templateDao.selectTemplateInfo(group, template);
        dealNewJsonTemplate(templateInfo);
        return Optional.ofNullable(templateInfo);
    } catch (EmptyResultDataAccessException ignore) {
        return Optional.empty();
    }
}
 
Example #24
Source File: ConfigEditorSettingsServiceImpl.java    From qconfig with MIT License 5 votes vote down vote up
@Override
public ConfigEditorSettings settingsOf(final String groupId, final String dataId) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(groupId), "groupId不能为空");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(dataId), "dataId不能为空");
    try {
        return configEditorSettingsDao.query(groupId, dataId);
    } catch (EmptyResultDataAccessException ignore) {
        return ConfigEditorSettings.DEFAULT;
    }
}
 
Example #25
Source File: UserDao.java    From poli with MIT License 5 votes vote down vote up
public User findByUsernameAndTempPassword(String username, String rawTempPassword) {
    String encryptedPassword = PasswordUtils.getMd5Hash(rawTempPassword);
    String sql = "SELECT id, username, name, sys_role "
                + "FROM p_user "
                + "WHERE username=? AND temp_password=?";
    try {
        User user = (User) jt.queryForObject(sql, new Object[]{username, encryptedPassword}, new UserInfoRowMapper());
        return user;
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #26
Source File: CommentRepository.java    From star-zone with Apache License 2.0 5 votes vote down vote up
public int countByMomentId(long momentId) {
    int count;
    final String sql = "SELECT COUNT(*) FROM " + TABLE_NAME + " WHERE moment_id=?";
    try {
        count = jdbcTemplate.queryForObject(sql, new Object[]{momentId}, new int[]{Types.BIGINT}
                , Integer.class);
    } catch (EmptyResultDataAccessException e) {
        count = 0;
    }
    return count;
}
 
Example #27
Source File: ShowDaoTests.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Test(expected=EmptyResultDataAccessException.class)
@Transactional
@Rollback(true)
public void testFindShowDetailByHost() {
    // TODO: Add code to setup a host and make the sow
    //  prefer the host, then check result again.
    showDao.getShowDetail(createHost());
}
 
Example #28
Source File: EntityManagerFactoryUtilsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
	EntityNotFoundException entityNotFound = new EntityNotFoundException();
	assertSame(JpaObjectRetrievalFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());

	NoResultException noResult = new NoResultException();
	assertSame(EmptyResultDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());

	NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
	assertSame(IncorrectResultSizeDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());

	OptimisticLockException optimisticLock = new OptimisticLockException();
	assertSame(JpaOptimisticLockingFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());

	EntityExistsException entityExists = new EntityExistsException("foo");
	assertSame(DataIntegrityViolationException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());

	TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
	assertSame(InvalidDataAccessApiUsageException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());

	PersistenceException unknown = new PersistenceException() {
	};
	assertSame(JpaSystemException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
 
Example #29
Source File: UserDao.java    From poli with MIT License 5 votes vote down vote up
public User findByShareKey(String shareKey) {
    String sql = "SELECT u.id, u.username, u.name, u.sys_role, u.session_key "
                + "FROM p_user u, p_shared_report sr "
                + "WHERE u.id = sr.user_id "
                + "AND sr.share_key=?";
    try {
        User user = (User) jt.queryForObject(sql, new Object[]{ shareKey }, new UserSesssionKeyMapper());
        return user;
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}
 
Example #30
Source File: SubscriptionDaoJdbc.java    From OpenCue with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isShowAtOrOverBurst(ShowInterface show, AllocationInterface alloc) {
    try {
        return getJdbcTemplate().queryForObject(IS_SHOW_AT_OR_OVER_BURST,
                Integer.class, show.getShowId(), alloc.getAllocationId()) > 0;
    } catch (EmptyResultDataAccessException e) {
        return true;
    }
}