Java Code Examples for org.springframework.dao.DataAccessException

The following examples show how to use org.springframework.dao.DataAccessException. 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
@Override
public Object invoke(MethodInvocation mi) throws Throwable {

	// Invoke the method potentially returning a reactive type
	Object m = mi.proceed();

	PersistenceExceptionTranslator translator = getPersistenceExceptionTranslator();
	if (translator == null) {
		return m;
	} else {
		// Add the translation. Nothing will happen if no-one subscribe the reactive result.
		Function<RuntimeException, Throwable> errorMappingFunction =
			t -> t instanceof DataAccessException ? t : DataAccessUtils.translateIfNecessary(t, translator);
		if (m instanceof Mono) {
			return ((Mono<?>) m).onErrorMap(RuntimeException.class, errorMappingFunction);
		} else if (m instanceof Flux) {
			return ((Flux<?>) m).onErrorMap(RuntimeException.class, errorMappingFunction);
		} else {
			return m;
		}
	}
}
 
Example 2
public boolean quickDelete(Object o) {
	try {
		getHibernateTemplate().delete(o);
		return true;
	} catch (DataAccessException | IllegalArgumentException e) {
		try {
			
			/* If we have multiple objects of the same item, you must merge them
			 * before deleting.  If the first delete fails, we merge and try again.
			 */
			getHibernateTemplate().delete(getHibernateTemplate().merge(o));
			
			return true;
		}catch(DataAccessException ex) {
			log.warn("Hibernate could not delete: " + e.toString());
			return false;
		}
	}
}
 
Example 3
Source Project: onetwo   Source File: SimpleRedisOperationService.java    License: Apache License 2.0 6 votes vote down vote up
/****
	 * 如果不存在,则设置
	 * @author weishao zeng
	 * @param key
	 * @param value
	 * @param seconds
	 * @return 设置成功,则返回所设置的值,否则返回已存在的值
	 */
	public boolean setNX(String key, Object value, int seconds) {
		final String cacheKey = getCacheKey(key);
		Boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {

			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
    			byte[] rawKey = getKeySerializer().serialize(cacheKey);
    			byte[] rawValue = getValueSerializer().serialize(value);
    			Boolean setOp = connection.setNX(rawKey, rawValue);
    			if (setOp!=null && setOp) {
    				connection.expire(rawKey, seconds);
    			}/* else {
    				rawValue = connection.get(rawKey);
    			}*/
//    			return (T)getValueSerializer().deserialize(rawValue);
    			return setOp;
    		}
    		
		});
    	return result;
    }
 
Example 4
Source Project: lams   Source File: HibernateTemplate.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public List<?> findByValueBean(final String queryString, final Object valueBean)
		throws DataAccessException {

	return executeWithNativeSession(new HibernateCallback<List<?>>() {
		@Override
		@SuppressWarnings({"rawtypes", "deprecation"})
		public List<?> doInHibernate(Session session) throws HibernateException {
			org.hibernate.Query queryObject = (org.hibernate.Query)
					ReflectionUtils.invokeMethod(createQueryMethod, session, queryString);
			prepareQuery(queryObject);
			queryObject.setProperties(valueBean);
			return queryObject.list();
		}
	});
}
 
Example 5
Source Project: bdf3   Source File: DbService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 查找sqlserver的主键索引
 * 
 * @param dbInofId
 * @param tableName
 * @return 返回主键索引的值
 * @throws Exception
 */
public String findSqlServerPKIndex(String dbInofId, final String tableName) throws Exception {
	DataSource ds = getDataSourceByDbInfoId(dbInofId);
	JdbcTemplate jdbcTemplate = SpringJdbcUtils.getJdbcTemplate(ds);
	String s = jdbcTemplate.execute(new ConnectionCallback<String>() {
		public String doInConnection(Connection con) throws SQLException, DataAccessException {
			String pkName = null;
			if (con.getMetaData().getURL().toLowerCase().contains("sqlserver")) {
				CallableStatement call = con.prepareCall("{call sp_pkeys(?)}");
				call.setString(1, tableName);
				ResultSet rs = call.executeQuery();
				while (rs.next()) {
					pkName = rs.getString("PK_NAME");
				}
			}
			return pkName;

		}
	});
	return s;
}
 
Example 6
Source Project: Breakpoint-http   Source File: AppTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRedisMap() {
    Object object = redisTemplate.execute(new SessionCallback() {
        @Override
        public Object execute(RedisOperations operations) throws DataAccessException {
            operations.multi();
            operations.opsForValue().get("test");
            operations.delete("test");
            operations.opsForValue().set("test", "6");
            List<String> rs = operations.exec();
            System.out.println(" rs:" + rs.toString());
            return rs;
        }
    });
    List<Object> strings = (List<Object>) object;
    for (Object str : strings) {
        System.err.println(str.toString());
    }
}
 
Example 7
Source Project: spring-analysis-note   Source File: HibernateTemplate.java    License: MIT License 6 votes vote down vote up
@Deprecated
@Override
@SuppressWarnings({"rawtypes", "unchecked", "deprecation"})
public List<?> findByNamedQueryAndNamedParam(
		final String queryName, @Nullable final String[] paramNames, @Nullable final Object[] values)
		throws DataAccessException {

	if (values != null && (paramNames == null || paramNames.length != values.length)) {
		throw new IllegalArgumentException("Length of paramNames array must match length of values array");
	}
	return nonNull(executeWithNativeSession((HibernateCallback<List<?>>) session -> {
		org.hibernate.Query queryObject = (org.hibernate.Query)
				nonNull(ReflectionUtils.invokeMethod(getNamedQueryMethod, session, queryName));
		prepareQuery(queryObject);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
			}
		}
		return queryObject.list();
	}));
}
 
Example 8
@Test
@SuppressWarnings("resource")
public void customErrorCodeTranslation() {
	new ClassPathXmlApplicationContext("test-custom-translators-context.xml",
			CustomSQLExceptionTranslatorRegistrarTests.class);

	SQLErrorCodes codes = SQLErrorCodesFactory.getInstance().getErrorCodes("H2");
	SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator();
	sext.setSqlErrorCodes(codes);

	DataAccessException exFor4200 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 42000));
	assertNotNull("Should have been translated", exFor4200);
	assertTrue("Should have been instance of BadSqlGrammarException",
		BadSqlGrammarException.class.isAssignableFrom(exFor4200.getClass()));

	DataAccessException exFor2 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 2));
	assertNotNull("Should have been translated", exFor2);
	assertTrue("Should have been instance of TransientDataAccessResourceException",
		TransientDataAccessResourceException.class.isAssignableFrom(exFor2.getClass()));

	DataAccessException exFor3 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 3));
	assertNull("Should not have been translated", exFor3);
}
 
Example 9
Source Project: lemon   Source File: SpringSessionSynchronization.java    License: Apache License 2.0 6 votes vote down vote up
public void beforeCommit(boolean readOnly) throws DataAccessException {
    if (!readOnly) {
        Session session = getCurrentSession();

        // Read-write transaction -> flush the Hibernate Session.
        // Further check: only flush when not FlushMode.MANUAL.
        if (!FlushMode.isManualFlushMode(session.getFlushMode())) {
            try {
                logger.debug("Flushing Hibernate Session on transaction synchronization");
                session.flush();
            } catch (HibernateException ex) {
                throw SessionFactoryUtils
                        .convertHibernateAccessException(ex);
            }
        }
    }
}
 
Example 10
Source Project: SimpleFlatMapper   Source File: PreparedStatementCallbackImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<T> doInPreparedStatement(PreparedStatement ps) throws SQLException,
		DataAccessException {
	ResultSet rs = ps.executeQuery();
	try {
		return resultSetExtractor.extractData(rs);
	} finally {
		rs.close();
	}
}
 
Example 11
Source Project: java-technology-stack   Source File: CciTemplate.java    License: MIT License 5 votes vote down vote up
/**
 * Execute the specified interaction on an EIS with CCI.
 * All other interaction execution methods go through this.
 * @param spec the CCI InteractionSpec instance that defines
 * the interaction (connector-specific)
 * @param inputRecord the input record
 * @param outputRecord output record (can be {@code null})
 * @param outputExtractor object to convert the output record to a result object
 * @return the output data extracted with the RecordExtractor object
 * @throws DataAccessException if there is any problem
 */
@Nullable
protected <T> T doExecute(
		final InteractionSpec spec, final Record inputRecord, @Nullable final Record outputRecord,
		@Nullable final RecordExtractor<T> outputExtractor) throws DataAccessException {

	return execute((InteractionCallback<T>) (interaction, connectionFactory) -> {
		Record outputRecordToUse = outputRecord;
		try {
			if (outputRecord != null || getOutputRecordCreator() != null) {
				// Use the CCI execute method with output record as parameter.
				if (outputRecord == null) {
					RecordFactory recordFactory = getRecordFactory(connectionFactory);
					outputRecordToUse = getOutputRecordCreator().createRecord(recordFactory);
				}
				interaction.execute(spec, inputRecord, outputRecordToUse);
			}
			else {
				outputRecordToUse = interaction.execute(spec, inputRecord);
			}
			return (outputExtractor != null ? outputExtractor.extractData(outputRecordToUse) : null);
		}
		finally {
			if (outputRecordToUse instanceof ResultSet) {
				closeResultSet((ResultSet) outputRecordToUse);
			}
		}
	});
}
 
Example 12
Source Project: audit4j-demo   Source File: JdbcVisitRepositoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void save(Visit visit) throws DataAccessException {
    if (visit.isNew()) {
        Number newKey = this.insertVisit.executeAndReturnKey(
                createVisitParameterSource(visit));
        visit.setId(newKey.intValue());
    } else {
        throw new UnsupportedOperationException("Visit update not supported");
    }
}
 
Example 13
public Set<SurveyDefinition> surveyDefinition_findAllPublishedInternal(User user) throws DataAccessException{
	if (user.isAdmin()){
		return surveyDefinitionDAO.findAllPublishedInternal(-1, -1);
	}
	else {
		return surveyDefinitionDAO.findAllPublishedInternal(user.getLogin(),-1, -1);
	}
}
 
Example 14
Source Project: spring-data   Source File: ArangoTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean exists(final Object id, final Class<?> entityClass) throws DataAccessException {
	try {
		return _collection(entityClass).documentExists(determineDocumentKeyFromId(id));
	} catch (final ArangoDBException e) {
		throw translateExceptionIfPossible(e);
	}
}
 
Example 15
Source Project: spring-analysis-note   Source File: StoredProcedureTests.java    License: MIT License 5 votes vote down vote up
public StoredProcedureExceptionTranslator(DataSource ds) {
	setDataSource(ds);
	setSql(SQL);
	getJdbcTemplate().setExceptionTranslator(new SQLExceptionTranslator() {
		@Override
		public DataAccessException translate(String task, @Nullable String sql, SQLException ex) {
			return new CustomDataException(sql, ex);
		}
	});
	compile();
}
 
Example 16
Source Project: java-technology-stack   Source File: HibernateTemplate.java    License: MIT License 5 votes vote down vote up
@Deprecated
@Override
public void closeIterator(Iterator<?> it) throws DataAccessException {
	try {
		Hibernate.close(it);
	}
	catch (HibernateException ex) {
		throw SessionFactoryUtils.convertHibernateAccessException(ex);
	}
}
 
Example 17
/**
 * Set the exception class for the specified error codes.
 */
public void setExceptionClass(@Nullable Class<?> exceptionClass) {
	if (exceptionClass != null && !DataAccessException.class.isAssignableFrom(exceptionClass)) {
		throw new IllegalArgumentException("Invalid exception class [" + exceptionClass +
				"]: needs to be a subclass of [org.springframework.dao.DataAccessException]");
	}
	this.exceptionClass = exceptionClass;
}
 
Example 18
@SuppressWarnings("unchecked")
@Override
@Transactional
public SortedSet<Invitation> searchByLastName(String lastName)	throws DataAccessException {
	Query query = createNamedQuery("Invitation.searchByLastName", -1, -1 , "%" + lastName +"%" );
	return new TreeSet<Invitation>(query.getResultList());
}
 
Example 19
Source Project: spring4-understanding   Source File: HibernateTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(Object proxy) throws DataAccessException {
	try {
		Hibernate.initialize(proxy);
	}
	catch (HibernateException ex) {
		throw SessionFactoryUtils.convertHibernateAccessException(ex);
	}
}
 
Example 20
Source Project: spring-data   Source File: ArangoTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> void upsert(final Iterable<T> value, final UpsertStrategy strategy) throws DataAccessException {
	final Optional<T> first = StreamSupport.stream(value.spliterator(), false).findFirst();
	if (!first.isPresent()) {
		return;
	}
	final Class<T> entityClass = (Class<T>) first.get().getClass();
	final ArangoPersistentEntity<?> entity = getConverter().getMappingContext().getPersistentEntity(entityClass);

	final Collection<T> withId = new ArrayList<>();
	final Collection<T> withoutId = new ArrayList<>();
	for (final T e : value) {
		final Object id = getDocumentKey(entity, e);
		if (id != null && (!(e instanceof Persistable) || !Persistable.class.cast(e).isNew())) {
			withId.add(e);
			continue;
		}
		withoutId.add(e);
	}
	if (!withoutId.isEmpty()) {
		insert(withoutId, entityClass);
	}
	if (!withId.isEmpty()) {
		switch (strategy) {
		case UPDATE:
			update(withId, entityClass);
			break;
		case REPLACE:
		default:
			replace(withId, entityClass);
			break;
		}
	}
}
 
Example 21
Source Project: sakai   Source File: PollListManagerImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
public boolean saveOption(Option t) {
    if (t.getUuid() == null 
            || t.getUuid().trim().length() == 0) {
        t.setUuid( UUID.randomUUID().toString() );
    }

    try {
        dao.save(t);
    } catch (DataAccessException e) {
        log.error("Hibernate could not save: " + e.toString(), e);
        return false;
    }
    log.info("Option  " + t.toString() + "successfuly saved");
    return true;
}
 
Example 22
Source Project: java-technology-stack   Source File: HibernateTemplate.java    License: MIT License 5 votes vote down vote up
@Override
public Serializable save(final String entityName, final Object entity) throws DataAccessException {
	return nonNull(executeWithNativeSession(session -> {
		checkWriteOperationAllowed(session);
		return session.save(entityName, entity);
	}));
}
 
Example 23
/**
 * Unbind the Hibernate {@code Session} from the thread and close it).
 * @see TransactionSynchronizationManager
 */
@Override
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
	if (!decrementParticipateCount(request)) {
		SessionHolder sessionHolder =
				(SessionHolder) TransactionSynchronizationManager.unbindResource(getSessionFactory());
		logger.debug("Closing Hibernate Session in OpenSessionInViewInterceptor");
		SessionFactoryUtils.closeSession(sessionHolder.getSession());
	}
}
 
Example 24
/**
 * {@inheritDoc}
 */
public boolean saveSiteSetupUserAnswer(SiteSetupUserAnswer siteSetupUserAnswer)
{
	try 
	{
		getHibernateTemplate().saveOrUpdate(siteSetupUserAnswer);
		return true;
	}
	catch (DataAccessException e)
	{
	 	log.warn("Hibernate could not save. Site={} user={} question={}", siteSetupUserAnswer.getSiteId(), siteSetupUserAnswer.getUserId(), siteSetupUserAnswer.getQuestionId(), e);
		return false;
	}
}
 
Example 25
Source Project: spring4-understanding   Source File: HibernateTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(Object proxy) throws DataAccessException {
	try {
		Hibernate.initialize(proxy);
	}
	catch (HibernateException ex) {
		throw SessionFactoryUtils.convertHibernateAccessException(ex);
	}
}
 
Example 26
Source Project: sdmq   Source File: RedisSupport.java    License: Apache License 2.0 5 votes vote down vote up
public Boolean setNx(final String key, final String value) {
    final org.springframework.data.redis.serializer.RedisSerializer redisSerializer      = template.getKeySerializer();
    final org.springframework.data.redis.serializer.RedisSerializer redisValueSerializer = template.getValueSerializer();
    return template.execute(new RedisCallback<Boolean>() {
        @Override
        public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
            return connection.setNX(redisSerializer.serialize(key), redisValueSerializer.serialize(value));
        }
    });
}
 
Example 27
Source Project: cobarclient   Source File: CobarSqlMapClientTemplate.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void update(String statementName, Object parameterObject, int requiredRowsAffected)
        throws DataAccessException {
    int rowAffected = this.update(statementName, parameterObject);
    if (rowAffected != requiredRowsAffected) {
        throw new JdbcUpdateAffectedIncorrectNumberOfRowsException(statementName,
                requiredRowsAffected, rowAffected);
    }
}
 
Example 28
Source Project: effectivejava   Source File: NamedParameterJdbcTemplate.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T> List<T> query(String sql, Map<String, ?> paramMap, RowMapper<T> rowMapper)
		throws DataAccessException {

	return query(sql, new MapSqlParameterSource(paramMap), rowMapper);
}
 
Example 29
Source Project: bootshiro   Source File: ResourceServiceImpl.java    License: MIT License 4 votes vote down vote up
@Override
public List<AuthResource> getNotAuthorityApisByRoleId(Integer roleId) throws DataAccessException {
    return authResourceMapper.selectNotAuthorityApisByRoleId(roleId);
}
 
Example 30
Source Project: java-technology-stack   Source File: HibernateTemplate.java    License: MIT License 4 votes vote down vote up
@Override
@Nullable
public Object get(String entityName, Serializable id) throws DataAccessException {
	return get(entityName, id, null);
}