I'm working on a project made with :
Web Dynamic Project + JPA 2.1 / EclipseLink 2.5.2
Tomcat 8.0.28 / JRE 1.8.0_66
Eclipse Luna
JPA part of the project was running fine when executed in a simple JPA project as a Java Application.
I made no changes on that part of the code.
I wanted to print some request results in a JSP. I generated a servlet and tried to print the name of a user already created in the database. For hours I had errors about JDBC driver and persistence.xml not found.
In order to solve dependancies problems I added Maven.
Now, my user is printed in the JSP and that's fine, but my "Run.java" class I used previously doesn't work anymore.
I'm quiet lost with the error I get when running my app as a "Java Application" :
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.<clinit>(EntityManagerFactoryProvider.java:55)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:92)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:188)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at dao.LayerDAO.<init>(LayerDAO.java:16)
at exec.Run.main(Run.java:18)
Caused by: java.lang.NullPointerException
at org.eclipse.persistence.platform.server.NoServerPlatformDetector.checkPlatform(NoServerPlatformDetector.java:28)
at org.eclipse.persistence.platform.server.ServerPlatformUtils.detectServerPlatform(ServerPlatformUtils.java:58)
at org.eclipse.persistence.internal.jpa.IsolatedHashMap.<clinit>(IsolatedHashMap.java:48)
... 7 more
Clearly the error occurs when I'm creating the EntityManagerFactory in the DAO class (the same one that is working with the JSP).
Here is my POM :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>CitizenWeb</groupId>
<artifactId>com.citizenweb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Generic properties -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
<!-- Test -->
<junit.version>4.11</junit.version>
</properties>
<dependencies>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- EclipseLink -->
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.core</artifactId>
<version>2.5.2</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.5.2</version>
</dependency>
<!-- MySQL DB -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
</dependencies>
</project>
If needed, here is my persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="CitizenWeb" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<mapping-file>META-INF/orm.xml</mapping-file>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/citizen"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.password" value="user"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
Entities mapping is managed with an orm.xml
Here's also the beginning of the DAO class :
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import entities.Address;
import entities.GroupAssoc;
import entities.RightsGranted;
import entities.User;
public class LayerDAO implements IFLayerDAOLocal {
EntityManager em = Persistence.createEntityManagerFactory("CitizenWeb").createEntityManager();
public void createUser(User user) {
System.out.println("DAO > addUser > "+em.hashCode());
em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();
}
Nothing has been changed here, neither in the persistence.xml
The "only" changes are in the build.path because of the change in the nature of project (JPA -> Web Dynamic+JPA). Maven has solved the problem with the webserver and the mysql connector, but now the app side is broken.
Do you see something I don't ?
Thanx.
In the buildpath of the project, I added an alternate "JRE System Library".
I previously had : JDK 1.8.0_66
I added : JRE 1.8.0_66
Now JSP works and also java Run class.
Related
I have created an app that uses JPA as well as servlets with JAX-RS.
When I run the app locally, I am able to query my server with curl and get the proper response for all the GET and POST requests. However, when I host the server on IBM Cloud and I query it with curl I get the error: "No Persistence provider for EntityManager".
What's causing the discrepancy between the local and remote (IBM Cloud) environments and what can I do to fix it?
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ibmcloud">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>java:comp/DefaultDataSource</non-jta-data-source>
<class>entities.Comment</class>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
</properties>
</persistence-unit>
</persistence>
.travis.yml
language: java
jdk: oraclejdk8
sudo: false
before_install:
mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V
before_deply:
cf login -u $BLUEMIX_USER -o $BLUEMIX_ORG
script:
mvn test -B
language: java
git:
depth: 1
dist: trusty
cache:
directories:
- "$HOME/.m2"
deploy:
edge: true
provider: bluemixcloudfoundry
username: $BLUEMIX_USER
password: $BLUEMIX_PASSWORD
organization: $BLUEMIX_ORG
space: $BLUEMIX_SPACE
manifest: manifest.yml
app_name: ibmcloudapp
region: eu-gb
api: https://api.eu-gb.bluemix.net
skip_cleanup: true
manifest.yml
applications:
- name: ibmcloud
path: target/ibmcloud.war
instances: 1
random-route: true
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dotheminimum</groupId>
<artifactId>ibmcloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
<!-- <dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency> -->
<!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
</plugins>
</build>
</project>
The source code for the app is hosted here
The problem was that my "persistence.xml" file was under "src/main/java/META-INF" instead of "src/main/resources/META-INF".
My local environment was able to find the file, but IBM Cloud didn't. After changing the path of "persistence.xml", the file was detected by IBM Cloud.
If I had been exhaustive, I would have been able to find my solution in the comments of the first result of the search linked to by Billy Frost (No Persistence provider for EntityManager named)
I am able to retrieve and persist an Entity without listing it in persistence.xml, but if I want to use a #NamedQuery, it doesn't work unless I list it in persistence.xml. Is there a way around this?
I am using Tomcat 8 with OpenJPA 2.4.2.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence
version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<!-- Used for persisting events, authentication pieces -->
<persistence-unit name="PushPersistence" transaction-type="RESOURCE_LOCAL">
<!-- Use Apache's OpenJPA -->
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<!-- Our backing store is our data source from context.xml -->
<non-jta-data-source>java:comp/env/jdbc/webservice</non-jta-data-source>
<!--
Without this, I can load and persist the entity but
CANNOT use Named Queries
-->
<class>push.authentication.AuthCredentials</class>
<!-- Don't require listing the managed classes here -->
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="openjpa.DynamicEnhancementAgent" value="true"/>
<property name="openjpa.RuntimeUnenhancedClasses" value="supported"/>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrettyPrint=true, PrettyPrintLineLength=72, PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=60000"/>
</properties>
</persistence-unit>
</persistence>
Maven:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>MyProj</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<!-- Tell Maven what language version to use -->
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.enterprise/cdi-api -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
</dependency>
<!-- Enables the annotations, etc needed -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<exclusions>
<exclusion>
<groupId>javax.exterprise</groupId>
<artifactId>cdi-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Our jersey libs -->
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.25.1</version>
</dependency>
<!-- CDI to JAX-RS Binding -->
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.containers.glassfish/jersey-gf-cdi-ban-custom-hk2-binding -->
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>2.14</version>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld.servlet/weld-servlet-core -->
<dependency>
<groupId>org.jboss.weld.servlet</groupId>
<artifactId>weld-servlet-core</artifactId>
<version>3.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jboss.weld/weld-core-impl -->
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-core-impl</artifactId>
<version>3.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>2.4.2</version>
</dependency>
</dependencies>
<build>
<!-- We don't use the version number in the war file name -->
<finalName>MyProj</finalName>
<plugins>
<!-- Enhances the JPA classes -->
<plugin>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>2.4.2</version>
<executions>
<execution>
<id>JPA Enhance</id>
<phase>process-classes</phase>
<goals>
<goal>enhance</goal>
</goals>
<configuration>
<includes>**/push/*.class</includes>
<persistenceXmlFile>${project.basedir}/src/main/resources/META-INF/persistence.xml</persistenceXmlFile>
<toolProperties>
<property>
<name>addDefaultConstructor</name>
<value>false</value>
</property>
<property>
<name>enforcePropertyRestrictions</name>
<value>true</value>
</property>
</toolProperties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Class declaration of named query:
package push;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Base64;
import java.util.Date;
#Entity
#NamedQueries(
{
#NamedQuery(
name = "Users.findByName",
query = "SELECT ac FROM Users ac WHERE ac.userName = :userName"
)
}
)
#Table(name = "PushClient")
public class Users
{
...
}
I read the EntityManager Interface and it says it throws IllegalArgumentException if a query has not been defined with the given name or if the query string is found to be invalid or if the query result is found to not be assignable to the specified type and if get IllegalArgumentException based on your snippet of code I think the third one is your case, try to use
EntityManager.createNamedQuery(java.lang.String name);
instead of
EntityManager.createNamedQuery(java.lang.String name,
java.lang.Class<T> resultClass);
And see if you get the same result or not
I have a multi module project, organised and built with maven. It consists of a war-module, an ejb-module and an ear-module. They alle have the same parent project (for dependencymanagement). Structure is like:
|- parent (packaging pom)
|-- ejb-module
|-- war-module
|-- ear-module
Built order is first ejb-module then war-module than ear-module. The project depends on arquillian for testing. Both ejb-module and war-module contain a test. When I run "mvn clean test -Parq-wildfly-managed" (profile is to activate testing) the test of ejb-module is executed, but the test of war-module is not executed and there is no surefire-report in the target folder. There is no additional information on the output. I just get the message "No tests were executed". The War-Module depends on the Ejb-Module and
Parent-Pom
<modelVersion>4.0.0</modelVersion>
<groupId>de.wilhelm</groupId>
<artifactId>parent</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>ejb-module</module>
<module>web-module</module>
<module>ear-module</module>
</modules>
<properties>
<!-- Explicitly declaring the source encoding eliminates the following
message: -->
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
resources, i.e. build is platform dependent! -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- JBoss dependency versions -->
<version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>
<!-- Define the version of the JBoss BOMs we want to import to specify tested stacks. -->
<version.jboss.bom>8.2.1.Final</version.jboss.bom>
<version.wildfly>9.0.0.Alpha1</version.wildfly>
<!-- other plugin versions -->
<version.compiler.plugin>3.1</version.compiler.plugin>
<version.ear.plugin>2.10</version.ear.plugin>
<version.ejb.plugin>2.3</version.ejb.plugin>
<version.surefire.plugin>2.16</version.surefire.plugin>
<version.war.plugin>2.5</version.war.plugin>
<!-- maven-compiler-plugin -->
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.source>1.7</maven.compiler.source>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.2-b01</version>
<scope>provided</scope>
</dependency>
<!-- Define the version of the EJB jar so that we don't need
to repeat ourselves in every module -->
<dependency>
<groupId>de.wilhelm</groupId>
<artifactId>ejb-module</artifactId>
<version>${project.version}</version>
<type>ejb</type>
<scope>compile</scope>
</dependency>
<!-- Define the version of the WAR so that we don't need to repeat
ourselves in every module -->
<dependency>
<groupId>de.wilhelm</groupId>
<artifactId>web-module</artifactId>
<version>${project.version}</version>
<type>war</type>
<scope>compile</scope>
</dependency>
<!-- JBoss distributes a complete set of Java EE 7 APIs including
a Bill of Materials (BOM). A BOM specifies the versions of a "stack" (or
a collection) of artifacts. We use this here so that we always get the correct
versions of artifacts. Here we use the jboss-javaee-7.0-with-tools stack
(you can read this as the JBoss stack of the Java EE 7 APIs, with some extras
tools for your project, such as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate
stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras
from the Hibernate family of projects) -->
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<!-- The WildFly plugin deploys your ear to a local JBoss
AS container -->
<!-- Due to Maven's lack of intelligence with EARs we need
to configure the wildfly maven plugin to skip deployment for all modules.
We then enable it specifically in the ear module. -->
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>${version.wildfly.maven.plugin}</version>
<inherited>true</inherited>
<configuration>
<skip>true</skip>
</configuration>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
EJB-Module POM
<parent>
<artifactId>parent</artifactId>
<groupId>de.wilhelm</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-module</artifactId>
<packaging>ejb</packaging>
<name>EJB Module</name>
<dependencies>
<!-- Declare the APIs we depend on and need for compilation. All of
them are provided by JBoss WildFly -->
<!-- Import the EJB API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the CDI API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JPA API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- JSR-303 (Bean Validation) Implementation -->
<!-- Provides portable constraints such as #Email -->
<!-- Hibernate Validator is shipped in JBoss WildFly -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>provided</scope>
</dependency>
<!-- Test scope dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- Optional, but highly recommended -->
<!-- Arquillian allows you to test enterprise code such as EJBs and
Transactional(JTA) JPA from JUnit/TestNG -->
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.protocol</groupId>
<artifactId>arquillian-protocol-servlet</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-ejb-plugin</artifactId>
<version>${version.ejb.plugin}</version>
<configuration>
<!-- Tell Maven we are using EJB 3.1 -->
<ejbVersion>3.1</ejbVersion>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<!-- The default profile skips all tests, though you can tune it
to run just unit tests based on a custom pattern
Seperate profiles are provided for running all tests, including
Arquillian tests that execute in the specified container -->
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.surefire.plugin}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<!-- An optional Arquillian testing profile that executes tests
in your WildFly instance
This profile will start a new WildFly instance, and execute
the test, shutting it down when done
Run with: mvn clean test -Parq-wildfly-managed -->
<id>arq-wildfly-managed</id>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<!-- An optional Arquillian testing profile that executes tests
in a remote WildFly instance
Run with: mvn clean test -Parq-wildfly-remote -->
<id>arq-wildfly-remote</id>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-remote</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
</profiles>
WAR-Module POM
<parent>
<artifactId>parent</artifactId>
<groupId>de.wilhelm</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>web-module</artifactId>
<packaging>war</packaging>
<name>WAR Module</name>
<dependencies>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Dependency on the EJB module so we can use it's services if needed -->
<dependency>
<groupId>de.wilhelm</groupId>
<artifactId>ejb-module</artifactId>
<type>ejb</type>
<scope>provided</scope>
</dependency>
<!-- Import the JAX-RS API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the CDI API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JSF API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.faces</groupId>
<artifactId>jboss-jsf-api_2.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JPA API, we use provided scope as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- JSR-303 (Bean Validation) Implementation -->
<!-- Provides portable constraints such as #Email -->
<!-- Hibernate Validator is shipped in JBoss WildFly -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--Test scope dependencies-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- Optional, but highly recommended
Arquillian allows you to test enterprise code such as EJBs and
Transactional(JTA) JPA from JUnit/TestNG -->
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.protocol</groupId>
<artifactId>arquillian-protocol-servlet</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<!-- Java EE 7 doesn't require web.xml, Maven needs to catch up! -->
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<!-- The default profile skips all tests, though you can tune it
to run just unit tests based on a custom pattern
Seperate profiles are provided for running all tests, including
Arquillian tests that execute in the specified container -->
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.surefire.plugin}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<!-- An optional Arquillian testing profile that executes tests
in your WildFly instance
This profile will start a new WildFly instance, and execute
the test, shutting it down when done
Run with: mvn clean test -Parq-wildfly-managed -->
<id>arq-wildfly-managed</id>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<!-- An optional Arquillian testing profile that executes tests
in a remote WildFly instance
Run with: mvn clean test -Parq-wildfly-remote -->
<id>arq-wildfly-remote</id>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-remote</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
</profiles>
Test class of EJB-Module (gets executed)
#RunWith(Arquillian.class)
public class AccountEntityFacadeTest {
#Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class)
.addClasses(AccountEntity.class, AccountEntityFacade.class, AbstractFacade.class, AccountEntityBuilder.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") // activates CDI
.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource("test-ds.xml", "test-ds.xml");
}
#PersistenceContext(unitName = "primary")
public EntityManager em;
#Inject
AccountEntityFacade userFacade;
#Inject
AccountEntityBuilder accountBuilder;
#Before
public void prepare() throws Exception {
clearData();
}
private void clearData() throws Exception{
}
#After
public void clear() throws Exception {
}
#Test
public void crudOperations() {
// valid create operations
AccountEntity a = accountBuilder.buildMemberAccount("a#a", "a", "a");
AccountEntity b = accountBuilder.buildMemberAccount("b#b", "b", "b");
userFacade.create(a);
userFacade.create(b);
AccountEntity aLoaded = userFacade.find(a.getEmail());
assert(aLoaded.equals(a));
}
}
Test class of WAR-Module (not executed)
#RunWith(Arquillian.class)
public class AccountRestIT {
#Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class)
.addClasses(AccountRest.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") // activates CDI
.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource("test-ds.xml", "test-ds.xml");
}
#Inject
AccountRest accountRest;
#Before
public void prepare() throws Exception {
}
#After
public void clear() throws Exception {
}
#Test
public void testRestApi() {
Assert.assertTrue(true);
}
I already tried to remove the profiles and run tests on default but the war-module tests were still not recognized.
public class AccountRestIT vs. public class AccountEntityFacadeTest
surefire-maven-plugin does not recognize tests that ends with *IT. You should change it's name to *Test or use other technique. For reference see this answer.
I've been trying to get a simple skeleton app to run (and commit to the DB) using JPA, MySQL, Hibernate & Maven, however I'm having problems.
Listed below are my 2 trivial classes, my pom.xml, and my META-INF/persistence.xml
I can build the project without any problem (mvn clean install), however running it (mvn exec:java -Dexec.mainClass=com.foo.HelloWorld -X) causes an exception, with the following StackTrace.
Any help would be greatly appreciated!
Stacktrace:
org.apache.maven.lifecycle.LifecycleExecutionException: An exception occured while executing the Java class. null
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:719)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeStandaloneGoal(DefaultLifecycleExecutor.java:569)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:539)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:387)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:348)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:180)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:328)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:138)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:362)
at org.apache.maven.cli.compat.CompatibleMain.main(CompatibleMain.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occured while executing the Java class. null
at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:346)
at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:490)
at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:694)
... 17 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:291)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/engine/SessionImplementor;
at org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:167)
at org.hibernate.action.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:142)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:65)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
at org.hibernate.event.def.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:154)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:110)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:646)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:620)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:624)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:212)
at com.foo.HelloWorld.create(HelloWorld.java:32)
at com.foo.HelloWorld.main(HelloWorld.java:11)
... 6 more
I have the following two classes:
The Entity to store.
package com.foo;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Message {
#Id
#GeneratedValue
private int id;
#Basic
private String message;
public Message() {}
public Message(String message) {
this.message = message;
}
public String toString() {
return "Greeting id=" + id + ", message=" + message;
}
}
The Application:
package com.foo;
public class HelloWorld {
private javax.persistence.EntityManagerFactory emf;
private javax.persistence.EntityManager em;
private String PERSISTENCE_UNIT_NAME = "hello-world";
public static void main(String[] args) {
HelloWorld hello = new HelloWorld();
hello.initEntityManager();
hello.create();
// hello.read();
hello.closeEntityManager();
}
private void initEntityManager() {
emf = javax.persistence.Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = emf.createEntityManager();
}
private void closeEntityManager() {
em.close();
emf.close();
}
private void create() {
em.getTransaction().begin();
Message hello = new Message("hello world");
Message bye = new Message("goodbye, world");
Message[] messages = new Message[] {hello, bye};
for (Message m : messages) {
em.persist(m);
}
em.getTransaction().commit();
}
// private void read() {
// Message m = (Message)em.createQuery("select m from Message m").getSingleResult();
// System.out.println("Query returned: " + m);
// }
}
The following is my pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.treocht.hibernate.tutorial</groupId>
<artifactId>hibernate-tutorial</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>First Hibernate Tutorial</name>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.7</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.2.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.0.beta9a</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.13</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<!--
we dont want the version to be part of the generated war file name
-->
<finalName>${artifactId}</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
And I have this META-INF/persistence.xml file:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd"
version="1.0">
<persistence-unit name="hello-world" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.foo.Message</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/my_db" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.password" value="password" />
<property name="hibernate.connection.username" value="username" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
You're indeed using incompatible versions of Hibernate artifacts as this can be verified using the official Hibernate Compatibility Matrix. Don't rely on some random tutorial found around the net for that.
But since you're using Maven, you actually don't need to declare all Hibernate artifacts, just leverage the transitive dependencies. So just declare a dependency in the hibernate-entitymanager (especially if you're not sure of what you're doing):
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.4.0.GA</version><!-- for JPA 1.0 -->
</dependency>
And remove these hibernate, hibernate-core, hibernate-annotations, persistence-api, slf4j dependencies.
And if you want to change the version of the sfl4j-api artifact that you get transitively, you should do that in the dependency management section:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
</dependencyManagement>
Actually (and I'm sorry to say so) your whole pom is a big mess, try to spend some time cleaning it. Use mvn dependency:tree (or some visual fronted offered by your IDE) to do so.
And let me insist, don't rely on some random (and wrong) tutorial found around the net, leverage Maven transitive dependency mechanism.
PS: As of Hibernate 3.5, the various projects (Hibernate Annotation, Hibernate EntityManager) have been merged back to Hibernate Core and their versions are synchronized which simplifies a lot version management, even for Maven users.
There might be the conflicts in version.
compare it with this
This is now working, and my pom.xml looks like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.company.hibernate.tutorial</groupId>
<artifactId>hibernate-tutorial</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Hibernate Tutorial</name>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.com/maven2/</url>
</repository>
</repositories>
<dependencies>
<!-- Hibernate framework -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.4.0.GA</version><!-- for JPA 1.0 -->
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.13</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.6.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
I'm trying to create integration tests using hsqldb in an in memory mode. At the moment, I have to start the hsqldb server from the command line before running the unit tests. I would like to be able to control the hsqldb server from my integration tests. I can't seem to get this to all work out though from code.
Update:
This appears to work along with having a hibernate.cfg.xml file in the classpath:
org.hsqldb.Server.main(new String[]{});
and in my hibernate.cfg.xml file:
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:ww</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hbm2ddl.auto">update</property>
Update
It appears that this is only a problem when running the unit tests from within Eclipse using jUnit and the built in test runner. If I run
mvn test
they are executed correctly and there is no exception. Am I missing something as far as a dependency goes? I have generated the eclipse project using
mvn eclipse:eclipse
and my pom is:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myproject</groupId>
<artifactId>myproject</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>myproject</name>
<dependencies>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.1.0.4.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.8.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.4.0.GA</version>
</dependency>
<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-servlet-tester</artifactId>
<version>6.1.24</version>
<scope>test</scope>
</dependency>
<!-- Provided -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>servlet-api</artifactId>
<version>6.0.26</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>jsp-api</artifactId>
<version>6.0.26</version>
</dependency>
</dependencies>
<build>
<finalName>ww_main</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
Update
Ok, well not sure what exactly was going wrong here, but I seemed to have fixed it. I deleted all the files that HSQLDB created, as well as all of the created files in my Maven target folder, did a clean, recreated my eclipse .project using maven and refreshed the project in eclipse. I think I may have had something left over from a previous configuration that was throwing it off.
Thanks for everyone's help!
I use the following configuration (directly inspired by the Hibernate tutorial) without any problem:
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:foobar"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<mapping resource="..."/>
</session-factory>
</hibernate-configuration>
When using an in-memory HSQLDB, there is no need to start anything explicitly. Just use the mem: protocol and the in-memory database will get started from JDBC.
See also
Unit-Testing Hibernate With HSQLDB
Try appending this to the jdbc url:
;ifexists=true;shutdown=true;
In your shutdown method just do
Statement st = conn.createStatement();
st.execute("SHUTDOWN");
conn.close();
What about starting server through Runtime.getRuntime().exec("shell command here")? You have to do it only once for all tests, so it won't add too big lag.
Update
Ok, looks like you've solved it yourself :)
Update 2
To execute some code once before (or after) unit tests, you can
static class TestWrapper extends TestSetup {
TestWrapper(TestSuite suite) {
super(suite);
}
protected void setUp() throws Exception {
// start db
}
protected void tearDown() throws Exception {
// kill db
}
}
Then, just wrap your test set in it: new TestWrapper(suite)
Maybe this might help to start HSQL in server mode in a Unit test, but in the same JVM.
Sample code runs org.hsqldb.server.WebServer (i.e. port 80) but you may use org.hsqldb.server.Server. You may call setPort on either to override default port.
https://stackoverflow.com/a/37784679/15789
check my hsqldb maven plugin :
https://github.com/avianey/hsqldb-maven-plugin
You can just start/stop it like jetty-maven-plugin or tomee-maven-plugin for your tests :
<plugin>
<!-- current version -->
<groupId>fr.avianey.mojo</groupId>
<artifactId>hsqldb-maven-plugin</artifactId>
<version>1.0.0</version>
<!--
default value for in memory jdbc:hsqldb:hsql://localhost/xdb
override only values you want to change
-->
<configuration>
<driver>org.hsqldb.jdbcDriver</driver>
<path>mem:test</path>
<address>localhost</address>
<name>xdb</name>
<username>sa</username>
<password></password>
<validationQuery>SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS</validationQuery>
</configuration>
<!-- call start and stop -->
<executions>
<execution>
<id>start-hsqldb</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-hsqldb</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>