Guest User

Untitled

a guest
Mar 4th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.Statement;
  4. import java.util.List;
  5.  
  6. import javax.persistence.PersistenceException;
  7.  
  8. import junit.framework.TestCase;
  9.  
  10. import org.apache.log4j.Logger;
  11. import org.hibernate.HibernateException;
  12. import org.hibernate.Session;
  13. import org.hibernate.SessionFactory;
  14. import org.hibernate.Transaction;
  15. import org.hibernate.cfg.AnnotationConfiguration;
  16.  
  17. public abstract class HibernateTestCase extends TestCase {
  18.  
  19. protected String[] DEFAULT_SCHEMAS = {"SCHEMA1", "SCHEMA2", "SCHEMA3"};
  20. protected static Logger logger = Logger.getLogger(HibernateTestCase.class);
  21. protected SessionFactory sf;
  22. private String configFile = "hypersonic.cfg.xml";
  23.  
  24. protected void createSchemas(String[] schemas) throws Exception {
  25. Class.forName("org.hsqldb.jdbcDriver");
  26. Connection conn = DriverManager.getConnection("jdbc:hsqldb:.","sa","");
  27.  
  28. for(String schema: schemas) {
  29. Statement st = conn.createStatement();
  30. String createSchema = "create schema " + schema + " authorization dba";
  31. st.executeUpdate(createSchema);
  32. st.close();
  33. }
  34. conn.close();
  35. }
  36.  
  37. protected void dropSchemas(String[] schemas) throws Exception {
  38. Class.forName("org.hsqldb.jdbcDriver");
  39. Connection conn = DriverManager.getConnection("jdbc:hsqldb:.","sa","");
  40.  
  41. for(String schema: schemas) {
  42. Statement st = conn.createStatement();
  43. String dropSchema = "drop schema " + schema;
  44. st.executeUpdate(dropSchema);
  45. st.close();
  46. }
  47. conn.close();
  48. }
  49.  
  50. protected void setUp() throws Exception {
  51. createSchemas(DEFAULT_SCHEMAS);
  52.  
  53. Session session = null;
  54. try {
  55. sf = new AnnotationConfiguration().configure(configFile).buildSessionFactory();
  56. session = sf.openSession();
  57. Transaction tx = session.beginTransaction();
  58. insertData(session);
  59. tx.commit();
  60. } catch (Exception e) {
  61. throw new PersistenceException(e);
  62. } finally {
  63. session.close();
  64. }
  65. }
  66.  
  67. protected abstract void insertData(Session session) throws HibernateException;
  68.  
  69. protected <T> void doInsertData(List<T> list, Session session) {
  70. for(T t: list) {
  71. session.save(t);
  72. }
  73. }
  74.  
  75. protected void tearDown() throws Exception {
  76. sf.close();
  77. dropSchemas(DEFAULT_SCHEMAS);
  78. }
  79.  
  80. public String getConfigFile() {
  81. return configFile;
  82. }
  83.  
  84. public void setConfigFile(String configFile) {
  85. this.configFile = configFile;
  86. }
  87. }
Add Comment
Please, Sign In to add comment