日期:2014-05-16  浏览次数:20440 次

使用HSQLDB来作EJB3 EntityBean到Unit Test要点
  • add <property name="hibernate.hbm2ddl.auto" value="create-drop"/> to hibernate property this will re-create table when SessionFactory init, drop table when session factory close
  • add HSQLDB dependency into pom.xml
?
<dependency>
          <groupId>hsqldb</groupId>
          <artifactId>hsqldb</artifactId>
          <version>1.8.0.7</version>
          <scope>test</scope>
        </dependency>
  • ?prepare meta data, and insert the meta data into MemDB, now I use @Before annotation from Junit, so I need to test if we need to insert the data indead, because the method annotated by? @Before will be executed each time for test method

?

@Before
    public void prepareData() throws ServiceException {
        if($needPrePareData){
            executeSqlFile("init_data.sql");
        }
    }
private void executeSqlFile(String fileName){
        try{
            File refFile = new File(ClassLoader.getSystemResource(fileName).toURI());
            SqlFile sqlFile = new SqlFile(refFile,false,null);
            sqlFile.execute(dataSource.getConnection(), true);
        }catch(Exception e){
            System.out.println("exception when prepare Data ");
            e.printStackTrace();
        }
    }
  • ?use HSQLDB releated property
db.dialect=org.hibernate.dialect.HSQLDialect
db.driver=org.hsqldb.jdbcDriver
db.url=jdbc:hsqldb:mem:DBName
db.username=sa
db.passwd=
  • we can also use hibernate3-maven-plugin to generate ddl from JPA annotation
    • ?http://mojo.codehaus.org/maven-hibernate3/hibernate3-maven-plugin/
    • ?ref article here http://unmaintainable.wordpress.com/2008/04/12/hibernate3-schema-creation/
    • pay more attention on the <implementation>jpaconfiguration</implementation>, it indicate that the plugin will use jpa as default implemtation
<build>
  <plugins>
    <!-- other plugins ... -->
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>hibernate3-maven-plugin</artifactId>
      <version>2.2</version>
      <executions>
        <execution>
          <phase>process-classes</phase>
          <goals>
            <goal>hbm2ddl</goal>
          </goals>
        </execution>
      </executions>
      <configuration>
        <components>
          <component>
            <name>hbm2ddl</name>
            <implementation>jpaconfiguration</implementation>
          </component>
        </components>
        <componentProperties>
          <persistenceunit>Default</persistenceunit>
          <outputfilename>schema.ddl</outputfilename>
          <drop>false</drop>
          <create>true</create>
          <export>false</export>
          <format>true</format>
        </componentProperties>
      </configuration>
    </plugin>