Pphunit keeps giving error: [1049] Unknown database ':memory:' - mysql

I just started working with phpunit in Laravel 7. I run into a problem that I cannot find a solution for. I am using Laravel 7 with Xampp.
My phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpcd ..
cdit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="DB_CONNECTION" value="mysql"/>
<server name="DB_DATABASE" value=":memory:"/>
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>
My test function:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Tests\TestCase;
class ThreadsTest extends TestCase
{
use DatabaseMigrations;
public function test_a_user_can_browse_threads()
{
$response = $this->get('/threads');
$response->assertStatus(200);
}
}
When I run phpunit (vendor/phpunit/phpunit/phpunit) I get this:
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.
.E 2 / 2 (100%)
Time: 1.57 seconds, Memory: 20.00 MB
There was 1 error:
1) Tests\Feature\ThreadsTest::test_a_user_can_browse_threads
Illuminate\Database\QueryException: SQLSTATE[HY000] [1049] Unknown database ':memory:' (SQL:
SHOW FULL TABLES WHERE table_type = 'BASE TABLE')
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:671
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:631
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:339
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Schema\MySqlBuilder.php:99
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Schema\MySqlBuilder.php:48
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Console\WipeCommand.php:69
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Console\WipeCommand.php:46
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:33
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\Util.php:37
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:91
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:35
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\Container.php:592
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Command.php:134
C:\xampp\htdocs\forum\vendor\symfony\console\Command\Command.php:258
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Command.php:121
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Concerns\CallsCommands.php:56
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Concerns\CallsCommands.php:28
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Console\Migrations\FreshCommand.php:41
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:33
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\Util.php:37
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:91
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:35
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\Container.php:592
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Command.php:134
C:\xampp\htdocs\forum\vendor\symfony\console\Command\Command.php:258
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Command.php:121
C:\xampp\htdocs\forum\vendor\symfony\console\Application.php:911
C:\xampp\htdocs\forum\vendor\symfony\console\Application.php:264
C:\xampp\htdocs\forum\vendor\symfony\console\Application.php:140
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Application.php:93
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Application.php:185
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:263
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Testing\PendingCommand.php:171
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Testing\PendingCommand.php:291
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithConsole.php:52
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Testing\DatabaseMigrations.php:16
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:119
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:84
Caused by
PDOException: SQLSTATE[HY000] [1049] Unknown database ':memory:'
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:46
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connectors\MySqlConnector.php:24
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connectors\ConnectionFactory.php:184
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:926
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:961
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:405
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:331
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:631
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Connection.php:339
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Schema\MySqlBuilder.php:99
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Schema\MySqlBuilder.php:48
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Console\WipeCommand.php:69
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Console\WipeCommand.php:46
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:33
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\Util.php:37
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:91
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:35
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\Container.php:592
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Command.php:134
C:\xampp\htdocs\forum\vendor\symfony\console\Command\Command.php:258
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Command.php:121
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Concerns\CallsCommands.php:56
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Concerns\CallsCommands.php:28
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Database\Console\Migrations\FreshCommand.php:41
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:33
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\Util.php:37
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:91
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php:35
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Container\Container.php:592
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Command.php:134
C:\xampp\htdocs\forum\vendor\symfony\console\Command\Command.php:258
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Command.php:121
C:\xampp\htdocs\forum\vendor\symfony\console\Application.php:911
C:\xampp\htdocs\forum\vendor\symfony\console\Application.php:264
C:\xampp\htdocs\forum\vendor\symfony\console\Application.php:140
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Application.php:93
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Console\Application.php:185
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:263
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Testing\PendingCommand.php:171
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Testing\PendingCommand.php:291
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithConsole.php:52
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Testing\DatabaseMigrations.php:16
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:119
C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Foundation\Testing\TestCase.php:84
ERRORS!
Tests: 2, Assertions: 1, Errors: 1.
Also the tables in my MYSQL database are all deleted.
Any suggestions?
Kind regards,
Hubert

I'm guessing you want to run sqlite as a memory database, at least that is my preferred test setup.
To achieve this, you have to setup your env in testing like so. Right now you had the connection as Mysql, this can not use the memory setting as sqlite.
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>

Related

How configure TomEE and JPA

sorry for my bad english, (Im french :-D).
I want work with TomEE for JPA, but my configuration is bad i think.
I receive a exception when i try to connecte to my database (Mysql).
persistence.xml
<persistence-unit name="elevage" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>elevage</jta-data-source>
<non-jta-data-source>elevageUnmanaged</non-jta-data-source>
<class>com.test.ejb.BeanAnimal</class>
<properties>
<property name="openjpa.jdbc.DBDictionary" value="mysql" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
</properties>
</persistence-unit>
tomee.xml
<Resource id="elevage" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage2?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged true
DefaultAutoCommit false
</Resource>
<Resource id="elevageUnmanaged" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage2?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged false
</Resource>
Exception
AVERTISSEMENT: Unexpected exception from beforeCompletion; transaction will roll back
<openjpa-2.4.1-r422266:1730418 fatal general error> org.apache.openjpa.persistence.PersistenceException: user lacks privilege or object not found: OPENJPA_SEQUENCE_TABLE {SELECT SEQUENCE_VALUE FROM OPENJPA_SEQUENCE_TABLE WHERE ID = ? FOR UPDATE} [code=-5501, state=42501]
Request is a "SELECT" and i want take all data in my database. I have see documentation but the problem persiste.
Thank all for your answer !
(if you need more file, tell me :-) )
After a long time tearing my hair, I found a solution, if it can save time, here it is:
2 Configurations!
In development:
tomee.xml is not used, it is necessary to configure openejb.xml whose path is specified in the eclipse console, attention, the access is by hidden file
Path for my machine (Linux):
/home/user/eclipse-workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp2/conf/openejb.xml
At the bottom of the file, you have section "Resource", the configuration is identical to tomee.xml (you can find documentation at this adress : documentation for configuration tomee.xml
In production:
we forget openejb.xml, a configuration is identical but in tomee.xml
to finish, here is my configuration:
persistence.xml
<persistence version="2.0" 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
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="elevage" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>MyDataBase</jta-data-source>
<non-jta-data-source>MyDataBaseUnmanaged</non-jta-data-source>
<class>com.test.ejb.BeanAnimal</class>
<!-- <class>com.test.ejb.BeanUser</class>-->
<properties>
<property name="openjpa.jdbc.DBDictionary" value="mysql" />
<property name="openjpa.Log" value="DefaultLevel=WARN, Tool=INFO" />
</properties>
</persistence-unit>
openejb.xml (in development) and tomee.xml (in production)
<Resource id="MyDataBase" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged true
</Resource>
<Resource id="MyDataBaseUnmanaged" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/elevage?useLegacyDatetimeCode=false&serverTimezone=Australia/Sydney&useSSL=false
UserName root
Password pass
JtaManaged false
</Resource>

Playframework Hibernate JPA cannot connect to Database

I'm trying to configure Hibernate JPA to access database. Without using Hibernate JPA, It accesses to database well, but when using Hibernate JPA it does not.
I'm following this tutorial:
https://www.playframework.com/documentation/2.5.x/JavaJPA
These are my steps:
build.sbt
//Hibernate JPA
libraryDependencies ++= Seq( javaJpa, "org.hibernate" % "hibernate-entitymanager" % "5.1.0.Final" // replace by your jpa implementation )
//JPA
PlayKeys.externalizeResources := false
//Driver for mysql
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.36"
conf/application.conf
db {
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
default.driver = "com.mysql.jdbc.Driver"
default.url = "jdbc:mysql://localhost:3306/sakila"
default.username = root
default.password = "root"
default.jndiName=DefaultDS
jpa.default=defaultPersistenceUnit
default.logSql=true
}
conf/META_INF/persistence.xml
<persistence 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"
version="2.1">
<persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>DefaultDS</non-jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
</properties>
</persistence-unit>
</persistence>
Error messages:
! #70fdppp3i - Internal server error, for (GET) [/count] ->
play.api.Configuration$$anon$1: Configuration error[Cannot connect to database [jpa]]
at play.api.Configuration$.configError(Configuration.scala:154)
at play.api.Configuration.reportError(Configuration.scala:806)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:48)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:42)
at scala.collection.immutable.List.foreach(List.scala:381)
at play.api.db.DefaultDBApi.connect(DefaultDBApi.scala:42)
at play.api.db.DBApiProvider.get$lzycompute(DBModule.scala:72)
at play.api.db.DBApiProvider.get(DBModule.scala:62)
at play.api.db.DBApiProvider.get(DBModule.scala:58)
at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
Caused by: play.api.Configuration$$anon$1: Configuration error[either dataSource or dataSourceClassName is required]
at play.api.Configuration$.configError(Configuration.scala:154)
at play.api.PlayConfig.reportError(Configuration.scala:996)
at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:70)
at play.api.db.PooledDatabase.createDataSource(Databases.scala:199)
at play.api.db.DefaultDatabase.dataSource$lzycompute(Databases.scala:123)
at play.api.db.DefaultDatabase.dataSource(Databases.scala:121)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:142)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:138)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:44)
at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:42)
Caused by: java.lang.IllegalArgumentException: either dataSource or dataSourceClassName is required
at com.zaxxer.hikari.HikariConfig.validate(HikariConfig.java:785)
at play.api.db.HikariCPConfig.toHikariConfig(HikariCPModule.scala:141)
at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:57)
at play.api.db.HikariCPConnectionPool$$anonfun$1.apply(HikariCPModule.scala:54)
at scala.util.Try$.apply(Try.scala:192)
at play.api.db.HikariCPConnectionPool.create(HikariCPModule.scala:54)
at play.api.db.PooledDatabase.createDataSource(Databases.scala:199)
at play.api.db.DefaultDatabase.dataSource$lzycompute(Databases.scala:123)
at play.api.db.DefaultDatabase.dataSource(Databases.scala:121)
at play.api.db.DefaultDatabase.getConnection(Databases.scala:142)
Error message on screen:
How to solve it?
I'm using Play framework 2.5
I think your jpa.default property is in wrong place. Try like this:
db {
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
default.driver = "com.mysql.jdbc.Driver"
default.url = "jdbc:mysql://localhost:3306/sakila"
default.username = root
default.password = "root"
default.jndiName=DefaultDS
default.logSql=true
}
jpa.default=defaultPersistenceUnit

Rollback in MyBatis using JDBC (no Spring, no containers)

I've seen all sorts of posts on using Spring and MyBatis with transactions, but I'm facing a problem with rollbacks not working with plain old JDBC.
My ( test / throwaway) code is pretty simple : I open a session, insert a rec, throw an error on purpose and rollback the transaction. However, it always commits.
public static void main (String[] args){
//-- omitted for brevity
try {
org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sess = sqlSessionFactory.openSession(false);
BillsMapper mapper = sess.getMapper(BillsMapper.class);
BillState billState = new BillState();
billState.setBillId(-1);
billState.setLastName("TESTER");
billState.setFirstName("TESTER");
mapper.insert(billState);
logger.info("Post insert: key = {}", billState.getBillId());
if(1 == 1)
throw new RuntimeException("Error Thrown on purpose...testing rollback ");
sess.commit();
}catch(Exception e){
logger.error("Error: {}", e);
sess.rollback();
}finally{
sess.close();
logger.info("Finito!");
}
}
The logs show:
DEBUG | (BaseJdbcLogger.java:145) - ==> Preparing: insert into bills (users_userId, refId, firstName, ...
DEBUG | (BaseJdbcLogger.java:145) - ==> Parameters: 67(Integer), 67-120530180328(String), TESTER(String), ...
DEBUG | (BaseJdbcLogger.java:145) - <== Updates: 1
INFO | (TestAction.java:50) - Post insert: key = 2478
ERROR | (TestAction.java:56) - Error: {} java.lang.RuntimeException: Error Thrown on purpose...testing rollback at com.s2stest.TestAction.main(TestAction.java:53)
DEBUG | (JdbcTransaction.java:79) - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:122) - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:90) - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (PooledDataSource.java:344) - Returned connection 924748027 to pool.
Note the resetting of autocommit before closing the connection.... Would resetting autcommit before closing the SqlSession cause my rolled-back transaction to be committed? If so, is this a bug? Has anyone gotten JDBC working with transactions? I need it for testing, and I'd value some help. Right now, no transactions can be rolled back.
I've looked at the MyBatis source, and it indeed calls resetAutocommit before closing the connection. I'm using MySQL 5.6 and mysql-connector-java-5.1.36.jar for the driver if someone has a workaround that they've found.
--- UPDATE ---
mybatis-config.xml is as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="SLF4J" />
</settings>
<typeAliases>
<package name="com.ship2storage.domain" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mytestDb?zeroDateTimeBehavior=convertToNull" />
<property name="username" value="--shhh!!--" />
<property name="password" value="--shhh!!--" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ship2storage/db/maps/BillsMapper.xml" />
</mappers>
</configuration>
OK, I've found the answer by digging deeper into my setup. It seems that the MySQL storage engine I installed for my test DB is ISAM. ISAM does not support transactions. I switched to InnoDB using the following SQL tidbit, and transactions now work with JDBC:
ALTER TABLE bills ENGINE=InnoDB;
I haven't tried this, but it looks like you can also do this temporarily too:
SET default_storage_engine=InnoDB;
Hopefully this will help someone. The code/config posted above works.

Clustered datasource migration from JBoss AS 5 to Wildfly 8

We plan to migrate from Jboss 5 to Wildfly 8.2. On the database side, we have a three-node Galera cluster with MariaDB 10.
On Jboss 5, we had the following setting in the ds.xml file:
...
<connection-url>jdbc:mysql:loadbalance://ip-node1,ip-node2,ip-node3/DBname</connection-url>
...
Everything worked well on Jboss 5. But I can't achieve the same on Wildfly 8.2. From the management console I was able to add a non-clustered datasource without problems and it works.
Example URL: jdbc:mysql://ip-node1/DBname
But when I try to add the clustered URL as above, I get the following error:
Unexpected HTTP response: 500
Request
{
"address" => [
("subsystem" => "datasources"),
("xa-data-source" => "dsName")
],
"operation" => "test-connection-in-pool"
}
Response
Internal Server Error
{
"outcome" => "failed",
"failure-description" => "JBAS010440: failed to invoke operation: JBAS010447: Connection is not valid",
"rolled-back" => true
}
How could I connect Wildfly to a clustered datasource? I know that it is possible to plug an external load balancer like HAProxy but I would prefer to keep the architecture as simple as possible.
You have to mention the datasource in standalone.xml file inside wildfly-8.2.0.Final_1\standalone\configuration\ as shown below.
<datasource jndi-name="java:/jdbc/DB1" pool-name="PostgresDS" enabled="true" use-java-context="true">
<connection-url>jdbc:postgresql://localhost:5432/DB1</connection-url>
<driver>postgres</driver>
<security>
<user-name>DB1</user-name>
<password>DB1</password>
</security>
</datasource>
<datasource jndi-name="java:/jdbc/DB2" pool-name="PostgresDS1" enabled="true" use-java-context="true">
<connection-url>jdbc:postgresql://localhost:5432/DB2</connection-url>
<driver>postgres</driver>
<security>
<user-name>DB2</user-name>
<password>DB2</password>
</security>
</datasource>

wildfly registering mysql as a datasource

I have been trying to configure mysql as a datasource in wildfly. I am not sure what i am missing out, i get an error on startup .
I have the mysql-connector-java-5.0.8-bin.jar and the module.xml in the folder:
"/wildfly-8.1.0.Final/modules/system/layers/base/com/mysql/main"
below are the files
module.xml
<module xmlns="urn:jboss:module:1.1"
name="com.mysql">
<resources>
<resource-root path="mysql-connector-java-5.0.8.jar"/>
<!-- Insert resources here -->
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
<module name="javax.servlet.api" optional="true"/>
</dependencies>
</module>
standalone.xml
<datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
<driver>h2</driver>
<security>
<user-name>sa</user-name>
<password>sa</password>
</security>
</datasource>
<datasource jta="true" jndi-name="java:jboss/datasources/proj" pool-name="proj" enabled="true" use-java-context="true" use-ccm="true">
<connection-url>jdbc:mysql://localhost:3306</connection-url>
<driver>mysql</driver>
<security>
<user-name>root</user-name>
<password>admin123</password>
</security>
<statement>
<prepared-statement-cache-size>32</prepared-statement-cache-size>
<share-prepared-statements>true</share-prepared-statements>
</statement>
</datasource>
<drivers>
<driver name="mysql" module="com.mysql">
<xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
</driver>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
</drivers>
</datasources>
I have tested the jdbc connectivity with a standalone program in eclipse and it worked
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ConnectSql {
public static void main(String []args){
String userName = "root";
String pass = "admin123";
String url = "jdbc:mysql://localhost/";
String driver ="com.mysql.jdbc.Driver";
String db = "proj";
try{
//registering the driver.
Class.forName(driver);
Connection con = DriverManager.getConnection(url+db,userName,pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select f_name from t_users");
while(rs.next()){
System.out.println("name :"+rs.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(ClassNotFoundException cnf){
cnf.printStackTrace();
}
}
}
Referred to the below link and modified the module.xml
Wildfly 8.0.0 mysql problems with datasource
Here is a the error log i get on start up
02:45:17,169 ERROR [org.jboss.as.controller.management-operation]
(Controller Boot Thread) JBAS014613: Operation ("add") failed -
address: ([
("subsystem" => "datasources"),
("data-source" => "proj") ]) - failure description: {"JBAS014771: Services with missing/unavailable dependencies" => [
"jboss.data-source.java:jboss/datasources/proj is missing [jboss.jdbc-driver.mysql]",
"jboss.driver-demander.java:jboss/datasources/proj is missing [jboss.jdbc-driver.mysql]" ]} 02:45:17,175 ERROR
[org.jboss.as.controller.management-operation] (Controller Boot
Thread) JBAS014613: Operation ("add") failed - address: ([
("subsystem" => "datasources"),
("data-source" => "proj") ]) - failure description: {
"JBAS014771: Services with missing/unavailable dependencies" => [
"jboss.data-source.java:jboss/datasources/proj is missing [jboss.jdbc-driver.mysql]",
"jboss.driver-demander.java:jboss/datasources/proj is missing [jboss.jdbc-driver.mysql]"
],
"JBAS014879: One or more services were unable to start due to one or more indirect dependencies not being available." => {
"Services that were unable to start:" => [
"jboss.data-source.reference-factory.proj",
"jboss.naming.context.java.jboss.datasources.proj"
],
"Services that may be the cause:" => ["jboss.jdbc-driver.mysql"]
} }
To resolve the mysql datasource configuration issue on Wildfly i used the admin console to add the datasource and test it.
If you login to the web console and find the datasource you tried configuring disable
that a remove it . The standalone.xml and the module.xml get reset to the orginal.
Steps for accessing web console
Configure a new datasource :
name :mysql
JNDI :java:jboss/datasources/proj
Click next and enter the url (i used the below) and click enable and then click test
url : jdbc:mysql://localhost/proj
The test should show success
The changes to the standalone.xml and the module.xml are automatically made .
If you restart the server now it should start without any errors and you should be able to access the database from your web project
I have working configuration of mysql driver on wildfly.
<datasources>
// ...
<drivers>
// ...
<driver name="mysql" module="com.mysql.jdbc">
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<driver-class>com.mysql.jdbc.Driver</driver-class>
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
<xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class>
</driver>
</drivers>
</datasources>
The little difference seems to be presence of "driver-class" tag.
I hope it will help.
(Deploying mysql driver as a deployment also works and it's recommended way. https://docs.jboss.org/author/display/WFLY8/DataSource+configuration )
[edit]
I have mysql module under wildfly/modules/com/mysql/jdbc/main/ . I've noticed just now you module path doesn't correspond to module name. And I haven't find any doc's just yet, but I don't think you should mess with modules/system directory.
module.xml
<?xml version="1.0" ?>
<module xmlns="urn:jboss:module:1.1" name="com.mysql.jdbc">
<resources>
<resource-root path="mysql-connector-java-5.1.31-bin.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
</module>
Two things: I just got mine working, and have the driver and xml located in $JBOSS_HOME/modules/com/mysql/jdbc/main - I'm fairly new with this as well so I'm not sure if that matters. Another thing: I don't know if it is just a typo, but if it was just copied and pasted it looks like your JAR name is incorrect
<resource-root path="mysql-connector-java-5.0.8.jar"/>
when it should be
<resource-root path="mysql-connector-java-5.0.8-bin.jar"/>
I forgot the .jar in mine, and that ended up fixing it. Hope that helps!
This may happen when you download the mysql connector zip and uploading the zip as a deployment. But the correct way is to unzip your download and point to the contained jar.
There are three ways using which you can simply create datasource into wildfly
Using admin console
Manually adding into standalone.xml
Creating datasource file that is xml file.
Go to WildFly directory/standalone/deployments
Simplest way to create datasource xml with following content
<datasources xmlns="http://www.jboss.org/ironjacamar/schema">
<datasource jndi-name="APP_DS" pool-name="APP_DS" enabled="true" use-ccm="false">
<connection-url>jdbc:mysql://localhost:3306/DB_NAME</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver>mysql</driver>
<!-- sql to call when connection is created -->
<new-connection-sql>SELECT 1</new-connection-sql>
<pool>
<min-pool-size>5</min-pool-size>
<max-pool-size>50</max-pool-size>
</pool>
<security>
<user-name>username</user-name>
<password>password</password>
</security>
<!-- sql to call on an existing pooled connection when it is obtained from pool -->
<validation>
<check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
</validation>
<timeout>
<blocking-timeout-millis>300000</blocking-timeout-millis>
<idle-timeout-minutes>5</idle-timeout-minutes>
</timeout>
<statement>
<track-statements>true</track-statements>
</statement>
</datasource>
</datasources>