org.jooq.exception.DetachedException: Cannot execute query. No Connection configured - junit

I have jOOQ (3.11.11) + H2 + Spring app, in which I am trying to run a simple JUnit test for persistence, but failing to do so with exceptions.
Here is my application.properties file:
spring.datasource.url=jdbc:h2:mem:jooq-test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL
spring.datasource.platform=h2
spring.datasource.username = sa
spring.datasource.password =
And my test config class as:
#Configuration
public class DummyTestConfig {
#Bean
public DSLContext dsl() {
return DSL.using(SQLDialect.H2);
}
}
And my test case:
public class JooqRepositoryImplTest {
#MockBean
private PlatformCache platformCache;
#Autowired
private JooqRepositoryImpl JooqRepository;
private List<Entity> getDummyEntityList() {
List<Entity> data = new ArrayList<>();
for (int i = 0; i < 15; i++) {
data.add(getDummyEntity());
}
return data;
}
private Entity getDummyEntity() {
final Entity entity = new Entity();
entity.setCapacity(150);
return entity;
}
#Test
public void testDatabaseIsUp() {
assert(1 == JooqRepository.count());
}
#Test
public void testReplace() {
JooqRepository.getEntitiesByJDBC(124, "C", DirectionEnum.I, TrafficBucketEnum.D);
}
#Test
public void testSave() {
final List<Entity> data = getDummyEntityList();
JooqRepository.batchSaveByJDBC(data);
}
}
And my repository implementation:
#Repository
public class JooqRepositoryImpl implements CustomRepository {
#Autowired
private DSLContext dslContext;
public int count() {
return dslContext.fetchCount(MyTable.MY_TABLE);
}
#Transactional
#Override
public void batchSaveByJDBC(List<Entity> entities) {
dslContext.batchInsert(entities.parallelStream().map(convertEntityToRecord()).collect(Collectors.toList()));
}
private Function<Entity, Record> convertEntityToRecord() {
return entity -> {
final Record record = new Record();
record.setCapacity(entity.getCapacity());
return record;
};
}
#Override
public void batchReplaceByJDBC(List<Entity> entities) {
executeReplace(MyTable.MY_TABLE, entities.toArray());
}
public int executeReplace(Table<Record> table, Object[] values) {
return dslContext.execute("replace into {0} ({1}) values ({2})",
table,
dslContext.informationSchema(table).getColumns(),
DSL.list(Stream.of(values).map(DSL::val).collect(Collectors.toList()))
);
}
#Override
public void batchUpdateByJDBC(List<Entity> entities,
LegRoutingTO leg) {
dslContext.batchUpdate(entities.parallelStream().map(convertEntityToRecord()).collect(Collectors.toList()));
}
#Override
public void batchUpdateByJDBCPartial (
List<Entity> entities, LegRoutingTO leg) {
final Batch updates = dslContext.batch(
entities.parallelStream().map(convertEntityToRecord()).map(convertRecordToQuery()).collect(Collectors.toList()));
updates.execute();
}
private Function<Record, Query> convertRecordToQuery() {
return record -> {
final UpdateQuery<Record> query = dslContext.updateQuery(MyTable.MY_TABLE);
query.setRecord(record);
return query;
};
}
private Function<Record, Entity> convertRecordToEntity() {
return record -> {
final Entity entity = new Entity();
BeanUtils.copyProperties(record, entity);
return entity;
};
}
}
EDIT: My pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jooq</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<!-- Skip DB creation if the value of the skip.db.creation property is
true -->
<configuration>
<skip>${skip.db.creation}</skip>
</configuration>
<executions>
<!-- Execute SQL statements to the configured database -->
<execution>
<id>create-database-h2</id>
<phase>generate-sources</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<!-- Configure the database connection -->
<driver>org.h2.Driver</driver>
<url>jdbc:h2:~/sampledb;INIT=CREATE SCHEMA IF NOT EXISTS
sampledb</url>
<username>sa</username>
<password></password>
<!-- Ensure that our changes are committed automatically -->
<autocommit>true</autocommit>
<!-- Configure the location of the invoked SQL script -->
<srcFiles>
<srcFile>src/main/resources/schema.sql</srcFile>
</srcFiles>
</configuration>
</execution>
</executions>
<dependencies>
<!-- Because we use the H2 database, we have to add it as the dependency
of this plugin. -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${com.h2database.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<version>3.4.4</version>
<executions>
<!-- Generate the required class from the database -->
<execution>
<id>generate-h2</id>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<!-- Because we use the H2 database, we have to add it as the dependency
of this plugin. -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${com.h2database.version}</version>
</dependency>
</dependencies>
<configuration>
<!-- Configure the database connection -->
<jdbc>
<driver>org.h2.Driver</driver>
<url>jdbc:h2:~/sampledb;INIT=CREATE SCHEMA IF NOT EXISTS
FORECAST_MEASURES</url>
<user>sa</user>
<password></password>
</jdbc>
<generator>
<database>
<!-- Configure the used database dialect -->
<name>org.jooq.util.h2.H2Database</name>
<!-- Include all tables found from the PUBLIC schema -->
<includes>.*</includes>
<excludes></excludes>
<inputSchema>PUBLIC</inputSchema>
</database>
<!-- Generate classes for tables and records -->
<generate>
<records>true</records>
</generate>
<!-- Configure the target package and dirmectory -->
<target>
<packageName>com.xxxx.entity.jooq</packageName>
<directory>src/main/java</directory>
</target>
</generator>
</configuration>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<!--This plugin's configuration is used to store Eclipse m2e settings
only. It has no influence on the Maven build itself. -->
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>
org.codehaus.mojo
</groupId>
<artifactId>
sql-maven-plugin
</artifactId>
<versionRange>
[1.5,)
</versionRange>
<goals>
<goal>execute</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore></ignore>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
----------
When I try to run test cases, one of them passes (testBatchInsert) and the other two fail with following stacktrace:
org.jooq.exception.DetachedException: Cannot execute query. No Connection configured
at org.jooq_3.11.11.H2.debug(Unknown Source)
at org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:319)
at org.jooq.impl.AbstractResultQuery.fetchLazy(AbstractResultQuery.java:393)
at org.jooq.impl.AbstractResultQuery.fetchLazy(AbstractResultQuery.java:380)
at org.jooq.impl.AbstractResultQuery.fetchStream(AbstractResultQuery.java:351)
at org.jooq.impl.SelectImpl.fetchStream(SelectImpl.java:2716)
at com.xxxx.repository.implementation.JooqRepositoryImpl.getEntitiesByJDBC(JooqRepositoryImpl.java:159)
at com.xxxx.repository.implementation.JooqRepositoryImpl$$FastClassBySpringCGLIB$$8ff9f08.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:684)
at com.xxxx.repository.implementation.JooqRepositoryImpl$$EnhancerBySpringCGLIB$$923a185d.getEntitiesByJDBC(<generated>)
at com.xxxx.repository.implementation.JooqRepositoryImplTest.testReplace(JooqRepositoryImplTest.java:126)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:66)

The reason is your DSLContext configuration:
#Configuration
public class DummyTestConfig {
#Bean
public DSLContext dsl() {
return DSL.using(SQLDialect.H2);
}
}
It is not connected to your data source. Either, you need to inject your data source to this configuration and use that:
#Configuration
public class DummyTestConfig {
#Autowired
DataSource ds;
#Bean
public DSLContext dsl() {
return DSL.using(ds, SQLDialect.H2);
}
}
Or you don't do this at all and use the DSLContext that is injected by Spring boot. Add this to your application.properties file:
#jOOQ Configuration
spring.jooq.sql-dialect=H2
You can find an example project here: https://github.com/jOOQ/jOOQ/tree/master/jOOQ-examples/jOOQ-spring-boot-example

Related

Building a RESTful Web Service: https://spring.io/guides/gs/rest-service/ Tutorial

I'm following the Spring training guide „Build a restful web service“ The application throws an error when I try and access http://localhost:8080/greeting. The error is:
ERROR 17903 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = ] with root cause
Working on Ubuntu 20.04, openjdk version "11.0.14.1" 2022-02-08,
mvn -version:
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Java version: 1.8.0_312, vendor: Private Build, runtime: /usr/lib/jvm/java-8-openjdk-amd64/jre
Here are the relevant classes:
public class GreetingController {
private static final String template = "Hello, % s!";
private final AtomicLong counter = new AtomicLong();
public Greeting greeting(#RequestParam(value = "name",
defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
I used Spring Initializr and added the dependency Spring Web as in the guide. Also the line:
com.example.demo.DemoApplication : Starting DemoApplication using Java 17.0.1
Seems like it is expecting Java 17 to run it. I have used Java 11 and Maven 2.6.7 in initializr and java 11 is set on my local machine.
Thanks in advance for any help
DataSperling
Solution: In the class:
public class GreetingController
The line:
private static final String template = "Hello, % s!";
Should read:
private static final String template = "Hello, %s!";
Also the url neads to be:
http://localhost:8080/greeting
NOT
https://localhost:8080/greeting
SSL is not required.

SpringBoot application is running properly but the hibernate & MySql related properties are not working

#Configuration
#EnableJpaRepositories(basePackages =
"com.gmt.user",entityManagerFactoryRef =
"userEntityManager",transactionManagerRef = "userTransactionManager")
public class UserConfig {
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean userEntityManager(){
LocalContainerEntityManagerFactoryBean em= new LocalContainerEntityManagerFactoryBean();
em.setDataSource(userDatasource());
em.setPackagesToScan(new String[]{"com.gmt.user"});
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String,Object> properties = new HashMap<String, Object>();
properties.put("hibernate.hbm2ddl.auto","craete");
properties.put("hibernate.dialect","org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql","true");
em.setJpaPropertyMap(properties);
return em;
}
#Bean
#Primary
public DataSource userDatasource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/schema_name");
dataSource.setUsername("root");
dataSource.setPassword("password12");
return dataSource;
}
#Bean
#Primary
public PlatformTransactionManager userTransactionManager(){
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(userEntityManager().getObject());
return jpaTransactionManager;
}
}
Here is my SpringBoot Application
#SpringBootApplication
#ComponentScan(basePackages = "com.gmt")
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class})
public class Client {
public static void main(String[] args){
SpringApplication.run(Client.class,args);
System.out.println(" ***** Inside Spring Boot Application ***** ");
}
}
here is my 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>Simple_Spring</groupId>
<artifactId>Spring01</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
And i have placed model class and respective repository in same folder.Application is running properly without any errors but not getting connected to database and not creating tables in the schema.Please help me to solve this issue.
You have misspelled the hibernate.hbm2ddl.auto property value here:
properties.put("hibernate.hbm2ddl.auto","craete");
It has to be create, but you have it set to craete.
in your POM if you use spring-boot-starter-data-jpa no need to use the other artifacts of <groupId>org.hibernate</groupId> . "spring-boot-starter-data-jpa" will bring in Hibernate as default JPA provider, this may cuase dependency conflicts I have seen similar issues because of that.
So you are saying no error displayed? did you debug?
Also in spring boot youc an set your properties as:
spring.datasource.*
spring boot JPA will ready it automatically
To change the hibernate properties we will use prefix
`spring.jpa.properties.*`
with hibernate property name
On the basis of given data source URL, spring boot can automatically identify data source driver class. So we need not to configure driver class.
Edit 1 ________
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/concretepage
spring.datasource.username=root
spring.datasource.password=
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

Unable to get Web App to work with mysql 5.1 and wildfly 10

I created a simple mvn webapp in netbeans and got it to work with h2. But I'm unable to get it to work with mysql as a datasource.
I've deployed the mysql 5.1.38 connector to Wildfly and it deploys and connects fine. I've added mysql to my persistence.xml as shown below. But it won't connect. I can connect to mysql in wildfly, mysql client, and within the services tab in wildfly.
After a lot of effort and research, I'm kind of lost.
InitBean
package toofar.demo.session;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import toofar.demo.Person;
#Startup
#Singleton
public class InitBean {
#Inject
PersonFacade personFacade;
#PostConstruct
private void init() {
personFacade.create(new Person("sad", "Willy"));
System.err.println(personFacade.find("sad").getName());
}
}
PersonFacade
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import toofar.demo.Person;
#Stateless
public class PersonFacade extends AbstractFacade<Person> {
#PersistenceContext(unitName = "toofar_Demo_war_1.0PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PersonFacade() {
super(Person.class);
}
}
AbstractFacade
package toofar.demo.session;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Entity Person
package toofar.demo;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
#Id
String guid;
String name;
public Person() {
}
public Person(String guid, String name) {
this.guid = guid;
this.name = name;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
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>toofar</groupId>
<artifactId>Demo</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>Demo</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.1.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>unknown.binary</groupId>
<artifactId>hibernate-jpamodelgen-4.3.1.Final</artifactId>
<version>SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>unknown-jars-temp-repo</id>
<name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
<url>file:${project.basedir}/lib</url>
</repository>
</repositories>
</project>
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="toofar_Demo_war_1.0PU" transaction-type="JTA">
<jta-data-source>java:/toofar</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Error log and stack trace
21:11:07,301 INFO [org.jboss.as.jpa] (ServerService Thread Pool -- 87) WFLYJPA0010: Starting Persistence Unit (phase 2 of 2) Service 'Demo-1.0.war#toofar_Demo_war_1.0PU'
21:11:07,302 WARN [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (ServerService Thread Pool -- 87) IJ000604: Throwable while attempting to get a new connection: null: javax.resource.ResourceException: IJ031084: Unable to create connection
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:343)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:350)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:285)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1319)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:496)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:626)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:598)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:590)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:563)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:747)
at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)
at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:66)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874)
at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:154)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:117)
at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:182)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.resource.ResourceException: IJ031087: Failed to register DriverClass for: org.mysql.Driver
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:600)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:318)
... 36 more
Caused by: java.lang.ClassNotFoundException: org.mysql.Driver from [Module "com.h2database.h2:main" from local module loader #5fcd892a (finder: local module finder #8b87145 (roots: C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules,C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules\system\layers\base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:591)
... 37 more
21:11:07,349 WARN [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator] (ServerService Thread Pool -- 87) HHH000342: Could not obtain connection to query metadata : javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
21:11:07,349 INFO [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 87) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
21:11:07,349 INFO [org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl] (ServerService Thread Pool -- 87) HHH000422: Disabling contextual LOB creation as connection was null
21:11:07,350 INFO [org.hibernate.envers.boot.internal.EnversServiceImpl] (ServerService Thread Pool -- 87) Envers integration enabled? : true
21:11:07,364 WARN [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (ServerService Thread Pool -- 87) IJ000604: Throwable while attempting to get a new connection: null: javax.resource.ResourceException: IJ031084: Unable to create connection
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:343)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:350)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:285)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1319)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:496)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:626)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:598)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:590)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:563)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:747)
at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)
at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:66)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:629)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:620)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.determineAppropriateJdbcConnectionContext(JpaSchemaGenerator.java:402)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.access$100(JpaSchemaGenerator.java:55)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$GenerationProcess.execute(JpaSchemaGenerator.java:113)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.performGeneration(JpaSchemaGenerator.java:65)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:154)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:117)
at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:182)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.resource.ResourceException: IJ031087: Failed to register DriverClass for: org.mysql.Driver
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:600)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:318)
... 28 more
Caused by: java.lang.ClassNotFoundException: org.mysql.Driver from [Module "com.h2database.h2:main" from local module loader #5fcd892a (finder: local module finder #8b87145 (roots: C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules,C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules\system\layers\base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:591)
... 29 more
21:11:07,400 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 87) MSC000001: Failed to start service jboss.persistenceunit."Demo-1.0.war#toofar_Demo_war_1.0PU": org.jboss.msc.service.StartException in service jboss.persistenceunit."Demo-1.0.war#toofar_Demo_war_1.0PU": javax.persistence.PersistenceException: Unable to obtain JDBC Connection
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:172)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:117)
at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:667)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:182)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: Unable to obtain JDBC Connection
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:632)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:620)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.determineAppropriateJdbcConnectionContext(JpaSchemaGenerator.java:402)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.access$100(JpaSchemaGenerator.java:55)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$GenerationProcess.execute(JpaSchemaGenerator.java:113)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator.performGeneration(JpaSchemaGenerator.java:65)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:154)
... 7 more
Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:146)
at org.jboss.as.connector.subsystems.datasources.WildFlyDataSource.getConnection(WildFlyDataSource.java:66)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator$ConnectionProviderJdbcConnectionAccess.<init>(JpaSchemaGenerator.java:629)
... 15 more
Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:656)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:563)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.allocateConnection(AbstractConnectionManager.java:747)
at org.jboss.jca.adapters.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:138)
... 18 more
Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:343)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getLocalManagedConnection(LocalManagedConnectionFactory.java:350)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createManagedConnection(LocalManagedConnectionFactory.java:285)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.createConnectionEventListener(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:1319)
at org.jboss.jca.core.connectionmanager.pool.mcp.SemaphoreConcurrentLinkedDequeManagedConnectionPool.getConnection(SemaphoreConcurrentLinkedDequeManagedConnectionPool.java:496)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getSimpleConnection(AbstractPool.java:626)
at org.jboss.jca.core.connectionmanager.pool.AbstractPool.getConnection(AbstractPool.java:598)
at org.jboss.jca.core.connectionmanager.AbstractConnectionManager.getManagedConnection(AbstractConnectionManager.java:590)
... 21 more
Caused by: javax.resource.ResourceException: IJ031087: Failed to register DriverClass for: org.mysql.Driver
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:600)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.createLocalManagedConnection(LocalManagedConnectionFactory.java:318)
... 28 more
Caused by: java.lang.ClassNotFoundException: org.mysql.Driver from [Module "com.h2database.h2:main" from local module loader #5fcd892a (finder: local module finder #8b87145 (roots: C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules,C:\Users\tharper\Downloads\wildfly-10.0.0.Final\modules\system\layers\base))]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.jboss.jca.adapters.jdbc.local.LocalManagedConnectionFactory.getDriver(LocalManagedConnectionFactory.java:591)
... 29 more
21:11:07,452 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 1) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"Demo-1.0.war#toofar_Demo_war_1.0PU\"" => "org.jboss.msc.service.StartException in service jboss.persistenceunit.\"Demo-1.0.war#toofar_Demo_war_1.0PU\": javax.persistence.PersistenceException: Unable to obtain JDBC Connection
Caused by: javax.persistence.PersistenceException: Unable to obtain JDBC Connection
Caused by: java.sql.SQLException: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
Caused by: javax.resource.ResourceException: IJ000453: Unable to get managed connection for java:/toofar
Caused by: javax.resource.ResourceException: IJ031084: Unable to create connection
Caused by: javax.resource.ResourceException: IJ031087: Failed to register DriverClass for: org.mysql.Driver
Caused by: java.lang.ClassNotFoundException: org.mysql.Driver from [Module \"com.h2database.h2:main\" from local module loader #5fcd892a (finder: local module finder #8b87145 (roots: C:\\Users\\tharper\\Downloads\\wildfly-10.0.0.Final\\modules,C:\\Users\\tharper\\Downloads\\wildfly-10.0.0.Final\\modules\\system\\layers\\base))]"}}
21:11:07,464 INFO [org.jboss.as.server] (DeploymentScanner-threads - 1)
It turns out that wildfly was updating standalone.xml when I would do add a DS and netbeans was looking at standalone-full.xml

Integration testing Spring Boot based Microservices

I have read many of the guides about working with Spring Boot and RESTful services, and many of them contain information about running unit tests, most notably "Building an Application with Spring Boot". However, I haven't seen anything that gives an example on how to unit test a Spring Boot application that consumes/depends on other Spring Boot applications, as is common in cloud micro-services architecture. So, for example, we have the following Spring Boot services:
ServiceMediator,
Adapter1,
Adapter2
ServiceMediator calls Adapter1 or Adapter2, depending on the input.
Is there a way to start up the Spring Boot services Adapter1 and Adapter2 before starting and testing the ServiceMediator in a Spring JUnit test?
The process-exec-maven-plugin could be helpful as allows to start multiple java processes at pre-integration-test phase (as standard Spring Boot apps), and it automatically takes care of shutting them down in the post-integration-test phase.
NOTE: The integration test should be run at the integration-test phase for that the maven-failsafe-plugin should be configured with spring-boot-maven-plugin see.
Then to run our integration tests verify or higher maven Lifecycle should be targeted, because the integration-test phase is in fact located between package and verify Lifecycles see Default Lifecycles.
The following maven (pom.xml) configuration worked for me:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.3.5.RELEASE</version>
<executions>
<execution>
<id>pre-integration-test</id>
<goals>
<goal>start</goal>
</goals>
<configuration>
<skip>${integration-tests.skip}</skip>
</configuration>
</execution>
<execution>
<id>post-integration-test</id>
<goals>
<goal>stop</goal>
</goals>
<configuration>
<skip>${integration-tests.skip}</skip>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<skip>${integration-tests.skip}</skip>
<includes>
<include>**/*IT.java</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.bazaarvoice.maven.plugins</groupId>
<artifactId>process-exec-maven-plugin</artifactId>
<version>0.7</version>
<executions>
<execution>
<id>switchboard-process</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
<configuration>
<name>accounts-service</name>
<workingDir>/../../micro-service</workingDir>
<waitForInterrupt>false</waitForInterrupt>
<arguments>
<argument>java</argument>
<argument>-jar</argument>
<argument>${basedir}/../micro-service/target/micro-service-${project.version}-exec.jar</argument>
</arguments>
</configuration>
</execution>
<!--Stop all processes in reverse order-->
<execution>
<id>stop-all</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop-all</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Having an Integration Test class (WebServerIT) in test.java folder:
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = WebServerApp.class)
#WebIntegrationTest("server.port:0")
public class WebServerIT {
#Autowired
private WebApplicationContext webServerAppContext;
private MockMvc webServerMockMvc;
#Before
public void setUp() {
System.out.println("the test is set up");
webServerMockMvc = MockMvcBuilders.webAppContextSetup(webServerAppContext).build();
}
/**
* This test calls the WebServer's endpoint (/accounts/123456789) which in turn calls the micro-service rest api
* which is started using the process-exec-maven-plugin, otherwise the test would fail.
*/
#Test
public void testWebServerInteractionWithMicroService() throws Exception {
this.webServerMockMvc.perform(get("/accounts/123456789"))
.andExpect(status().isOk());
}
}
package controller;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.net.URL;
import mediator.CLPApplication;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = CLPApplication.class)
#WebAppConfiguration
#IntegrationTest()
public class ControllerTest {
#Value("${adapter.dependency.jar.location}")
private String adapterDependencyJarLocation;
#Value("${adapter.dependency.jar.name}")
private String adapterDependencyJarName;
#Value("${adapter.url}")
private String adapterURL;
#Value("${mediator.url}")
private String mediatorURL;
private URL mediator;
private URL adapter;
private RestTemplate template;
Process process = null;
#Before
public void setUp() throws Exception {
adapter = new URL(adapterURL);
template = new TestRestTemplate();
//
// Start the Atomic adapter
//
System.out.println(adapterDependencyJarLocation);
System.out.println("Starting Adapter");
try {
process = new ProcessBuilder("java", "-jar", adapterDependencyJarName)
.directory(new File(adapterDependencyJarLocation)).start();
// Try connecting 5 times with a 5 second pause between each
// to see if it started.
Thread.sleep(5000);
for(int i = 0; i <= 5; i++) {
try{
System.out.println("Testing to see if Adapter is up");
template.getForEntity(adapter.toString(), String.class);
System.out.println("Adapter Started");
break;
}
catch(RestClientException rce){
System.out.println("It's not up yet");
}
Thread.sleep(5000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Test
public void testMediator() throws Exception {
mediator = new URL(mediatorURL);
System.out.println("Calling Mediator");
ResponseEntity<String> response = template.getForEntity(mediator.toString(), String.class);
System.out.println(response.getBody());
// Getting back JSON, so check to see if it starts with an open bracket
assertThat(response.getBody(), Matchers.startsWith("{"));
}
#After
public void tearDown() {
if(process != null) {
process.destroy();
}
}
}

EJB testing with TomEE embedded EJBContainer api: java.lang.ClassFormatError exception

I would test my EJB with TomEE embedded EJBContainer.
This is my JUnit test case skeleton:
package com.xxx.indexer.scheduler.service;
import java.util.Properties;
import javax.ejb.embeddable.EJBContainer;
import javax.naming.NamingException;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.xxx.indexer.scheduler.AbstractTest;
public class BookingAuditServiceImplTest extends AbstractTest {
private static EJBContainer container;
#BeforeClass
public static void start() {
final Properties props = new Properties();
props.setProperty(EJBContainer.PROVIDER, "tomee-embedded");
container = EJBContainer.createEJBContainer(props);
}
#AfterClass
public static void stop() {
container.close();
}
#Before
public void inject() throws NamingException {
container.getContext().bind("inject", this);
}
#Test
public void test() {
// TODO
}
}
And these are my maven dependecies:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>tomee-embedded</artifactId>
<version>1.0.0</version>
<scope>test</scope>
</dependency>
When I start the test class, the EJBContainer.createEJBContainer() method throws a java.lang.ClassFormatError exception:
java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/ejb/embeddable/EJBContainer
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2308)
at java.lang.Class.getDeclaredFields(Class.java:1760)
at org.junit.runners.model.TestClass.<init>(TestClass.java:44)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:73)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:55)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:13)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:48)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
How can I do?
I read at this link, https://stackoverflow.com/a/3416368/1412839, that the problem is the order of maven dependencies.
I have to declare first the tomee embedded artifact, and after the javaee api, in this way:
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>tomee-embedded</artifactId>
<version>1.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
It works.
you can replace javax:javaee-api (broken jar) by org.apache.openejb:javaee-api:6.0-4 too and it always works ;)