org.hibernate.exception.ConstraintViolationException#org.springframework.dao.DataAccessResourceFailureException源码实例Demo

下面列出了org.hibernate.exception.ConstraintViolationException#org.springframework.dao.DataAccessResourceFailureException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
public void setBlobAsBinaryStream(
		PreparedStatement ps, int paramIndex, @Nullable InputStream binaryStream, int contentLength)
		throws SQLException {

	if (binaryStream != null) {
		Blob blob = ps.getConnection().createBlob();
		try {
			FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryBlobs.add(blob);
		ps.setBlob(paramIndex, blob);
	}
	else {
		ps.setBlob(paramIndex, (Blob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(binaryStream != null ?
				"Copied binary stream into temporary BLOB with length " + contentLength :
				"Set BLOB to null");
	}
}
 
@Override
public void setClobAsAsciiStream(
		PreparedStatement ps, int paramIndex, @Nullable InputStream asciiStream, int contentLength)
		throws SQLException {

	if (asciiStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(asciiStream != null ?
				"Copied ASCII stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
@Override
public void setBlobAsBinaryStream(
		PreparedStatement ps, int paramIndex, @Nullable InputStream binaryStream, int contentLength)
		throws SQLException {

	if (binaryStream != null) {
		Blob blob = ps.getConnection().createBlob();
		try {
			FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryBlobs.add(blob);
		ps.setBlob(paramIndex, blob);
	}
	else {
		ps.setBlob(paramIndex, (Blob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(binaryStream != null ?
				"Copied binary stream into temporary BLOB with length " + contentLength :
				"Set BLOB to null");
	}
}
 
@Override
public void setClobAsAsciiStream(
		PreparedStatement ps, int paramIndex, @Nullable InputStream asciiStream, int contentLength)
		throws SQLException {

	if (asciiStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(asciiStream != null ?
				"Copied ASCII stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
@Override
public void setClobAsCharacterStream(
		PreparedStatement ps, int paramIndex, @Nullable Reader characterStream, int contentLength)
		throws SQLException {

	if (characterStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(characterStream, clob.setCharacterStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(characterStream != null ?
				"Copied character stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
源代码8 项目: lams   文件: HibernateTemplate.java
/**
 * Return a Session for use by this template.
 * <p>Returns a new Session in case of "alwaysUseNewSession" (using the same
 * JDBC Connection as a transactional Session, if applicable), a pre-bound
 * Session in case of "allowCreate" turned off, and a pre-bound or new Session
 * otherwise (new only if no transactional or otherwise pre-bound Session exists).
 * @return the Session to use (never {@code null})
 * @see SessionFactoryUtils#getSession
 * @see SessionFactoryUtils#getNewSession
 * @see #setAlwaysUseNewSession
 * @see #setAllowCreate
 */
protected Session getSession() {
	if (isAlwaysUseNewSession()) {
		return SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor());
	}
	else if (isAllowCreate()) {
		return SessionFactoryUtils.getSession(
				getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
	}
	else if (SessionFactoryUtils.hasTransactionalSession(getSessionFactory())) {
		return SessionFactoryUtils.getSession(getSessionFactory(), false);
	}
	else {
		try {
			return getSessionFactory().getCurrentSession();
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException("Could not obtain current Hibernate Session", ex);
		}
	}
}
 
源代码9 项目: lams   文件: TemporaryLobCreator.java
@Override
public void setBlobAsBinaryStream(
		PreparedStatement ps, int paramIndex, InputStream binaryStream, int contentLength)
		throws SQLException {

	if (binaryStream != null) {
		Blob blob = ps.getConnection().createBlob();
		try {
			FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryBlobs.add(blob);
		ps.setBlob(paramIndex, blob);
	}
	else {
		ps.setBlob(paramIndex, (Blob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(binaryStream != null ?
				"Copied binary stream into temporary BLOB with length " + contentLength :
				"Set BLOB to null");
	}
}
 
源代码10 项目: lams   文件: TemporaryLobCreator.java
@Override
public void setClobAsAsciiStream(
		PreparedStatement ps, int paramIndex, InputStream asciiStream, int contentLength)
		throws SQLException {

	if (asciiStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(asciiStream != null ?
				"Copied ASCII stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
源代码11 项目: lams   文件: TemporaryLobCreator.java
@Override
public void setClobAsCharacterStream(
		PreparedStatement ps, int paramIndex, Reader characterStream, int contentLength)
		throws SQLException {

	if (characterStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(characterStream, clob.setCharacterStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(characterStream != null ?
				"Copied character stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
源代码12 项目: lams   文件: AbstractSequenceMaxValueIncrementer.java
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
@Override
public void preHandle(WebRequest request) throws DataAccessException {
	String key = getParticipateAttributeName();
	WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
	if (asyncManager.hasConcurrentResult() && applyEntityManagerBindingInterceptor(asyncManager, key)) {
		return;
	}

	EntityManagerFactory emf = obtainEntityManagerFactory();
	if (TransactionSynchronizationManager.hasResource(emf)) {
		// Do not modify the EntityManager: just mark the request accordingly.
		Integer count = (Integer) request.getAttribute(key, WebRequest.SCOPE_REQUEST);
		int newCount = (count != null ? count + 1 : 1);
		request.setAttribute(getParticipateAttributeName(), newCount, WebRequest.SCOPE_REQUEST);
	}
	else {
		logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewInterceptor");
		try {
			EntityManager em = createEntityManager();
			EntityManagerHolder emHolder = new EntityManagerHolder(em);
			TransactionSynchronizationManager.bindResource(emf, emHolder);

			AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder);
			asyncManager.registerCallableInterceptor(key, interceptor);
			asyncManager.registerDeferredResultInterceptor(key, interceptor);
		}
		catch (PersistenceException ex) {
			throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
		}
	}
}
 
/**
 * Open a Session for the given SessionFactory.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory to use
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @since 5.0
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	Session session = openSession();
	if (session == null) {
		try {
			session = sessionFactory.openSession();
			session.setFlushMode(FlushMode.MANUAL);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
		}
	}
	return session;
}
 
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = obtainSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
/**
 * Open a Session for the SessionFactory that this filter uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory that this filter uses
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	try {
		Session session = sessionFactory.openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
源代码17 项目: dubbox   文件: SolrExceptionTranslator.java
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex.getCause() instanceof SolrServerException) {
		SolrServerException solrServerException = (SolrServerException) ex.getCause();
		if (solrServerException.getCause() instanceof SolrException) {
			SolrException solrException = (SolrException) solrServerException.getCause();
			// solr 4.x moved ParseExecption from
			// org.apache.lucene.queryParser to
			// org.apache.lucene.queryparser.classic
			// therefore compare ShortClassName instead of using instanceof
			// expression
			if (solrException.getCause() != null && ClassUtils.getShortName(solrException.getCause().getClass())
					.equalsIgnoreCase("ParseException")) {
				return new InvalidDataAccessApiUsageException((solrException.getCause()).getMessage(),
						solrException.getCause());
			} else {
				ErrorCode errorCode = ErrorCode.getErrorCode(solrException.code());
				switch (errorCode) {
				case NOT_FOUND:
				case SERVICE_UNAVAILABLE:
				case SERVER_ERROR:
					return new DataAccessResourceFailureException(solrException.getMessage(), solrException);
				case FORBIDDEN:
				case UNAUTHORIZED:
					return new PermissionDeniedDataAccessException(solrException.getMessage(), solrException);
				case BAD_REQUEST:
					return new InvalidDataAccessApiUsageException(solrException.getMessage(), solrException);
				case UNKNOWN:
					return new UncategorizedSolrException(solrException.getMessage(), solrException);
				default:
					break;
				}
			}
		} else if (solrServerException.getCause() instanceof ConnectException) {
			return new DataAccessResourceFailureException(solrServerException.getCause().getMessage(),
					solrServerException.getCause());
		}
	}
	return null;
}
 
@Test
@SuppressWarnings("resource")
public void proxiesCorrectly() {
	GenericApplicationContext gac = new GenericApplicationContext();
	gac.registerBeanDefinition("translator",
			new RootBeanDefinition(PersistenceExceptionTranslationPostProcessor.class));
	gac.registerBeanDefinition("notProxied", new RootBeanDefinition(RepositoryInterfaceImpl.class));
	gac.registerBeanDefinition("proxied", new RootBeanDefinition(StereotypedRepositoryInterfaceImpl.class));
	gac.registerBeanDefinition("classProxied", new RootBeanDefinition(RepositoryWithoutInterface.class));
	gac.registerBeanDefinition("classProxiedAndAdvised",
			new RootBeanDefinition(RepositoryWithoutInterfaceAndOtherwiseAdvised.class));
	gac.registerBeanDefinition("myTranslator",
			new RootBeanDefinition(MyPersistenceExceptionTranslator.class));
	gac.registerBeanDefinition("proxyCreator",
			BeanDefinitionBuilder.rootBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class).
					addPropertyValue("order", 50).getBeanDefinition());
	gac.registerBeanDefinition("logger", new RootBeanDefinition(LogAllAspect.class));
	gac.refresh();

	RepositoryInterface shouldNotBeProxied = (RepositoryInterface) gac.getBean("notProxied");
	assertFalse(AopUtils.isAopProxy(shouldNotBeProxied));
	RepositoryInterface shouldBeProxied = (RepositoryInterface) gac.getBean("proxied");
	assertTrue(AopUtils.isAopProxy(shouldBeProxied));
	RepositoryWithoutInterface rwi = (RepositoryWithoutInterface) gac.getBean("classProxied");
	assertTrue(AopUtils.isAopProxy(rwi));
	checkWillTranslateExceptions(rwi);

	Additional rwi2 = (Additional) gac.getBean("classProxiedAndAdvised");
	assertTrue(AopUtils.isAopProxy(rwi2));
	rwi2.additionalMethod(false);
	checkWillTranslateExceptions(rwi2);
	try {
		rwi2.additionalMethod(true);
		fail("Should have thrown DataAccessResourceFailureException");
	}
	catch (DataAccessResourceFailureException ex) {
		assertEquals("my failure", ex.getMessage());
	}
}
 
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {
	if (ex instanceof PersistenceException) {
		return new DataAccessResourceFailureException(ex.getMessage());
	}
	return null;
}
 
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that @@identity
		* returns the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate(getIncrementStatement());
				ResultSet rs = stmt.executeQuery(getIdentityStatement());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("Identity statement failed after inserting");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			stmt.executeUpdate(getDeleteStatement(this.valueCache));
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
源代码21 项目: spring-analysis-note   文件: Jdbc4SqlXmlHandler.java
@Override
public void setValue(PreparedStatement ps, int paramIndex) throws SQLException {
	this.xmlObject = ps.getConnection().createSQLXML();
	try {
		provideXml(this.xmlObject);
	}
	catch (IOException ex) {
		throw new DataAccessResourceFailureException("Failure encountered while providing XML", ex);
	}
	ps.setSQLXML(paramIndex, this.xmlObject);
}
 
源代码22 项目: spring-analysis-note   文件: Jdbc4SqlXmlHandler.java
@Override
public void cleanup() {
	if (this.xmlObject != null) {
		try {
			this.xmlObject.free();
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not free SQLXML object", ex);
		}
	}
}
 
@Override
@Nullable
protected DataAccessException doTranslate(String task, @Nullable String sql, SQLException ex) {
	// First, the getSQLState check...
	String sqlState = getSqlState(ex);
	if (sqlState != null && sqlState.length() >= 2) {
		String classCode = sqlState.substring(0, 2);
		if (logger.isDebugEnabled()) {
			logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
		}
		if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
			return new BadSqlGrammarException(task, (sql != null ? sql : ""), ex);
		}
		else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
	}

	// For MySQL: exception class name indicating a timeout?
	// (since MySQL doesn't throw the JDBC 4 SQLTimeoutException)
	if (ex.getClass().getName().contains("Timeout")) {
		return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
	}

	// Couldn't resolve anything proper - resort to UncategorizedSQLException.
	return null;
}
 
@Test
public void errorCodeTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException badSqlEx = new SQLException("", "", 1);
	BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());

	SQLException invResEx = new SQLException("", "", 4);
	InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
	assertEquals("SQL", irsex.getSql());
	assertEquals(invResEx, irsex.getSQLException());

	checkTranslation(sext, 5, DataAccessResourceFailureException.class);
	checkTranslation(sext, 6, DataIntegrityViolationException.class);
	checkTranslation(sext, 7, CannotAcquireLockException.class);
	checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
	checkTranslation(sext, 9, CannotSerializeTransactionException.class);
	checkTranslation(sext, 10, DuplicateKeyException.class);

	SQLException dupKeyEx = new SQLException("", "", 10);
	DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
	assertTrue("Not instance of DataIntegrityViolationException",
			DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));

	// Test fallback. We assume that no database will ever return this error code,
	// but 07xxx will be bad grammar picked up by the fallback SQLState translator
	SQLException sex = new SQLException("", "07xxx", 666666666);
	BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
	assertEquals("SQL2", bsgex2.getSql());
	assertEquals(sex, bsgex2.getSQLException());
}
 
@Test
public void dataTruncationTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException dataAccessEx = new SQLException("", "", 5);
	DataTruncation dataTruncation = new DataTruncation(1, true, true, 1, 1, dataAccessEx);
	DataAccessResourceFailureException daex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataTruncation);
	assertEquals(dataTruncation, daex.getCause());
}
 
源代码26 项目: lams   文件: HibernateTransactionManager.java
@Override
protected Object doGetTransaction() {
	HibernateTransactionObject txObject = new HibernateTransactionObject();
	txObject.setSavepointAllowed(isNestedTransactionAllowed());

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found thread-bound Session [" +
					SessionFactoryUtils.toString(sessionHolder.getSession()) + "] for Hibernate transaction");
		}
		txObject.setSessionHolder(sessionHolder);
	}
	else if (this.hibernateManagedSession) {
		try {
			Session session = getSessionFactory().getCurrentSession();
			if (logger.isDebugEnabled()) {
				logger.debug("Found Hibernate-managed Session [" +
						SessionFactoryUtils.toString(session) + "] for Spring-managed transaction");
			}
			txObject.setExistingSession(session);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException(
					"Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);
		}
	}

	if (getDataSource() != null) {
		ConnectionHolder conHolder = (ConnectionHolder)
				TransactionSynchronizationManager.getResource(getDataSource());
		txObject.setConnectionHolder(conHolder);
	}

	return txObject;
}
 
/**
 * Open a Session for the given SessionFactory.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory to use
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @since 5.0
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	Session session = openSession();
	if (session == null) {
		try {
			session = sessionFactory.openSession();
			session.setFlushMode(FlushMode.MANUAL);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
		}
	}
	return session;
}
 
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = obtainSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
/**
 * Open a Session for the SessionFactory that this filter uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory that this filter uses
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	try {
		Session session = sessionFactory.openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
@Override
protected Object doGetTransaction() {
	HibernateTransactionObject txObject = new HibernateTransactionObject();
	txObject.setSavepointAllowed(isNestedTransactionAllowed());

	SessionFactory sessionFactory = obtainSessionFactory();
	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
	if (sessionHolder != null) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + "] for Hibernate transaction");
		}
		txObject.setSessionHolder(sessionHolder);
	}
	else if (this.hibernateManagedSession) {
		try {
			Session session = sessionFactory.getCurrentSession();
			if (logger.isDebugEnabled()) {
				logger.debug("Found Hibernate-managed Session [" + session + "] for Spring-managed transaction");
			}
			txObject.setExistingSession(session);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException(
					"Could not obtain Hibernate-managed Session for Spring-managed transaction", ex);
		}
	}

	if (getDataSource() != null) {
		ConnectionHolder conHolder = (ConnectionHolder)
				TransactionSynchronizationManager.getResource(getDataSource());
		txObject.setConnectionHolder(conHolder);
	}

	return txObject;
}