View Javadoc

1   /*
2    *  Copyright 2001-2007 Stephen Colebourne
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   */
16  package org.joda.time.contrib.hibernate;
17  
18  import junit.framework.TestCase;
19  
20  import org.hibernate.SessionFactory;
21  import org.hibernate.cfg.Configuration;
22  import org.hibernate.dialect.HSQLDialect;
23  import org.hibernate.tool.hbm2ddl.SchemaUpdate;
24  
25  import java.sql.Connection;
26  import java.sql.Statement;
27  
28  public abstract class HibernateTestCase extends TestCase
29  {
30  	private SessionFactory factory;
31      private Configuration cfg;
32  
33      protected SessionFactory getSessionFactory()
34  	{
35  		if (this.factory == null)
36  		{
37                      cfg = new Configuration();
38  
39                      setupConfiguration(cfg);
40  
41  			cfg.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver");
42  			cfg.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:hbmtest" + getClass().getName());
43  			cfg.setProperty("hibernate.dialect", HSQLDialect.class.getName());
44  
45  			cfg.setProperty("hibernate.show_sql", "true");
46  			SessionFactory factory = cfg.buildSessionFactory();
47  
48  			SchemaUpdate update = new SchemaUpdate(cfg);
49  			update.execute(true, true);
50  
51  			this.factory = factory;
52  		}
53  		return factory;
54  	}
55  
56  	protected void tearDown() throws Exception
57  	{
58              final String[] dropSQLs = cfg.generateDropSchemaScript(new HSQLDialect());
59              final Connection connection = getSessionFactory().openSession().connection();
60              try {
61                  Statement stmt = connection.createStatement();
62                  for (int i = 0; i < dropSQLs.length; i++) {
63                      //System.out.println("dropSQLs[i] = " + dropSQLs[i]);
64                      stmt.executeUpdate(dropSQLs[i]);
65                  }
66              } finally {
67                  connection.close();
68              }
69  
70              if (this.factory != null)
71  		{
72  			this.factory.close();
73  			this.factory = null;
74  		}
75  	}
76  
77  	protected abstract void setupConfiguration(Configuration cfg);
78  }