org.springframework.dao.DataAccessException Java Examples

The following examples show how to use org.springframework.dao.DataAccessException. 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: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 7 votes vote down vote up
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 #2
Source File: HibernateTemplate.java    From spring-analysis-note with 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 #3
Source File: CustomSQLExceptionTranslatorRegistrarTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: HibernateTemplate.java    From spring4-understanding with Apache License 2.0 6 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 #5
Source File: ReactivePersistenceExceptionTranslationInterceptor.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: SiteSetupQuestionServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * {@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 #7
Source File: AppTest.java    From Breakpoint-http with 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 #8
Source File: SimpleRedisOperationService.java    From onetwo with 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 #9
Source File: HibernateTemplate.java    From lams with 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 #10
Source File: DbService.java    From bdf3 with 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 #11
Source File: SpringSessionSynchronization.java    From lemon with 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 #12
Source File: PollListManagerImpl.java    From sakai with 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 #13
Source File: ArangoTemplate.java    From spring-data with 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 #14
Source File: CobarSqlMapClientTemplate.java    From cobarclient with 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 #15
Source File: SurveySettingsService.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #16
Source File: JdbcVisitRepositoryImpl.java    From audit4j-demo with 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 #17
Source File: ArangoTemplate.java    From spring-data with 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 #18
Source File: HibernateTemplate.java    From spring4-understanding with 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 #19
Source File: CciTemplate.java    From java-technology-stack with 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 #20
Source File: PreparedStatementCallbackImpl.java    From SimpleFlatMapper with 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 #21
Source File: RedisSupport.java    From sdmq with 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 #22
Source File: HibernateTemplate.java    From java-technology-stack with 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
Source File: OpenSessionInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
Source File: InvitationDAOImpl.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #25
Source File: StoredProcedureTests.java    From spring-analysis-note with 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 #26
Source File: CustomSQLErrorCodesTranslation.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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 #27
Source File: HibernateTemplate.java    From java-technology-stack with 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 #28
Source File: AuthorityDAOImpl.java    From JDeSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Set<Authority> findAllExternal() throws DataAccessException {
	return findAllExternal(-1, -1);
}
 
Example #29
Source File: JdbcTemplate.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public <T> List<T> queryForList(String sql, Object[] args, int[] argTypes, Class<T> elementType) throws DataAccessException {
	return query(sql, args, argTypes, getSingleColumnRowMapper(elementType));
}
 
Example #30
Source File: HibernateTemplate.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Object load(String entityName, Serializable id) throws DataAccessException {
	return load(entityName, id, null);
}