1 package org.hibernate.test.exception; 3 4 import java.sql.Connection ; 5 import java.sql.PreparedStatement ; 6 import java.sql.SQLException ; 7 8 import junit.framework.Test; 9 import junit.framework.TestSuite; 10 11 import org.hibernate.JDBCException; 12 import org.hibernate.Session; 13 import org.hibernate.dialect.MySQLMyISAMDialect; 14 import org.hibernate.exception.ConstraintViolationException; 15 import org.hibernate.exception.SQLExceptionConverter; 16 import org.hibernate.exception.SQLGrammarException; 17 import org.hibernate.test.TestCase; 18 import org.hibernate.util.JDBCExceptionReporter; 19 20 25 public class SQLExceptionConversionTest extends TestCase { 26 27 public SQLExceptionConversionTest(String name) { 28 super(name); 29 } 30 31 protected String [] getMappings() { 32 return new String [] {"exception/User.hbm.xml", "exception/Group.hbm.xml"}; 33 } 34 35 public void testIntegrityViolation() throws Exception { 36 if ( getDialect() instanceof MySQLMyISAMDialect ) return; 37 38 SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter(); 39 40 Session session = openSession(); 41 Connection connection = session.connection(); 42 43 try { 46 PreparedStatement ps = connection.prepareStatement("INSERT INTO T_MEMBERSHIP (user_id, group_id) VALUES (?, ?)"); 47 ps.setLong(1, 52134241); ps.setLong(2, 5342); ps.executeUpdate(); 50 ps.close(); 51 52 fail("INSERT should have failed"); 53 } 54 catch(SQLException sqle) { 55 JDBCExceptionReporter.logExceptions(sqle, "Just output!!!!"); 56 JDBCException jdbcException = converter.convert(sqle, null, null); 57 assertEquals( "Bad conversion [" + sqle.getMessage() + "]", ConstraintViolationException.class , jdbcException.getClass() ); 58 ConstraintViolationException ex = (ConstraintViolationException) jdbcException; 59 System.out.println("Violated constraint name: " + ex.getConstraintName()); 60 } 61 62 session.close(); 63 } 64 65 public void testBadGrammar() throws Exception { 66 SQLExceptionConverter converter = getDialect().buildSQLExceptionConverter(); 67 68 Session session = openSession(); 69 Connection connection = session.connection(); 70 71 try { 73 PreparedStatement ps = connection.prepareStatement("SELECT user_id, user_name FROM tbl_user"); 74 ps.executeQuery(); 75 ps.close(); 76 77 fail("SQL compilation should have failed"); 78 } 79 catch( SQLException sqle ) { 80 assertEquals( "Bad conversion [" + sqle.getMessage() + "]", SQLGrammarException.class, converter.convert(sqle, null, null).getClass() ); 81 } 82 83 session.close(); 84 } 85 86 public static Test suite() { 87 return new TestSuite(SQLExceptionConversionTest.class); 88 } 89 } 90 | Popular Tags |