I am using hiberante jpa to connect to a mysql database.
My persistence-unit in my persistence.xml looks like this:
<persistence-unit name="inventoryManager">
<!--some settings-->
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/inventory?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="1234"/>
<!--Hibernate properties-->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
</properties>
</persistence-unit>
My DAO´s are using this connection to execute all the operations with the database.
I am also using DBUnit for the tests, but I am using an in-memory database(hsql). and its configuration in my test case constructor looks like this:
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS, "org.hsqldb.jdbcDriver" );
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL, "jdbc:hsqldb:mem:db" );
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME, "sa" );
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD, "" );
System.setProperty( PropertiesBasedJdbcDatabaseTester.DBUNIT_SCHEMA, "db" );
So when I run a test that calls one DAO. The DAO instantiates an entityManager which points to the mysql connetion specified in the persistence.xml
The question is: How do I make the entityManager inside my DAO to point to my in-memory database?
Thanks in advance!
As you are not using Spring you can try a Maven based solution. This involves creating a separate persistence.xml under src/test/resources/META-INF with the relevant properties.
When running your tests this persistence.xml should take precedence over the one in src/main/resources.
You can do something like below:
1.Create a datasource bean pointing to In Memory DB something like below
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="org.hsqldb.jdbc.JDBCDriver" />
<property name="jdbcUrl"
value="jdbc:hsqldb:file:/data/data.db" />
</bean>
2.Define a EntityManagerFactory which will refer to this DataSource.
3.Add both these beans in a testConfig.xml
4.Run with JUnit
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations ={ "testconfig.xml" })
Related
I am getting Application must provide JDBC connection exception while trying to perform query on Mysql DB using Spring+hibernate
Application context has following entry
<bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="appDataSource" />
</bean>
<bean id="appDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://localhost:3306/appdb" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
And JNDI name as
<jee:jndi-lookup id="appDataSource" jndi-name="java:comp/env/jdbc/Modeling"/>
Complete stack trace
java.lang.UnsupportedOperationException: The application must supply JDBC connections
at org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl.getConnection(UserSuppliedConnectionProviderImpl.java:44)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:84)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java: )
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.connection(StatementPreparerImpl.java:47)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1927)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1896)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1874)
at org.hibernate.loader.Loader.doQuery(Loader.java:919)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2610)
at org.hibernate.loader.Loader.doList(Loader.java:2593)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2422)
at org.hibernate.loader.Loader.list(Loader.java:2417)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1339)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
at org.hibernate.internal.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:964)
Hibernate configuration
<hibernate-configuration>
<session-factory>
<mapping resource="service.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Service.hbm.xml file
<hibernate-mapping>
<class name="service.repository.Account"
table="ACCOUNTS" discriminator-value="null">
<id name="id" column="id" type="java.lang.Long">
//all other entry
</class>
</hibernate-mapping>
Do the below -
1)check hibernate.cgf.xml(or your hibernate config file) & confirm if below are correct -
hibernate.connection.url
hibernate.connection.username
hibernate.connection.password
hibernate.dialect
hibernate.connection.driver_class
2) Check for the datasource name you have define in your standalone.xml(JBoss config file).It should match with your jndi-name ="java:datasource_name"
I assume your "java:comp/env/jdbc/Modeling" JNDI name does not point to a valid data source object.
Issue is solved after removing Jrebel plugin from server settings.
Some how jrebel was messing with the configuration.
Upgraded rebel configuration and things are working fine now.
If not resolved yet them try giving path of hibernate.cfg.xml to configure object
cfg.configure("hibernate.cfg.xml");
and also can skip dialect property in xml if you are not able to select right one for yourself .
it worked for me.
I have a REST service which access a MySQL database. I'm using Wildfly 10 and MySQL 5.7.12. I am trying to get the EntityManager as an injection and I get the following error when executing the find method for my Entity mapping the table content.
org.h2.jdbc.JdbcSQLException: Table "MYTABLE" not found; SQL statement:
In the RESTService class I have
#PersistenceContext(unitName="myUnit")
protected EntityManager entityManager;
and my persistence.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<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="myUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/mytable" />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="pass" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.archive.autodetection" value="class, hbm"/>
</properties>
</persistence-unit>
</persistence>
The issue is that if instead of using injection I retrieve the entity manager using the manual way everything works smothly.
EntityManagerFactory emFactory;
emFactory = Persistence.createEntityManagerFactory("myUnit");
EntityManager em = emFactory.createEntityManager();
Could you give me some hints on how to use the PersistenceContext? the code is somehow cleaner and I prefer to use it.
It looks like you 're getting the default datasource injected in your persistence Unit so I guess this depends on how the EntityManager is 'built'. One way to fix this is to create a datasource in WidFly and use it (through) its JNDI name in your persistence unit.
Feel free to report a bug http://issues.jboss.org/
You are setting up a RESOURCE_LOCAL persistence unit. You should configure it as such:
<persistence-unit transaction-type="RESOURCE_LOCAL">
In order to use a resource local persistence unit you cannot inject EntityManager, only EntityManagerFactory. You'll end up with a lot less plumbing if you switch to JTA datasource and let the server manage it.
If you absolutely don't want to edit standalone.xml, in WF8 anyway, you can drop yourdatasource-ds.xml file into your WEB-INF folder, or into the deployments directory alongside your .war file. There was talk of removing this from WF though so I don't know if it works in 10.x.
I'm developing a Play 2.3 Application with JPA/Hibernate and use a Heroku/ClearDB.com MySQL Database for this but after the application connects successfully to the DB I get following error:
[error] c.j.b.h.AbstractConnectionHook - Failed to acquire connection to jdbc:mysql://eu-cdbr-west-01.cleardb.com:3306/heroku_b7ea7b2d2972532 Sleeping for 1000ms and trying again. Attempts left: 10. Exception: null.Message:User 'badd25925bdd5f' has exceeded the 'max_user_connections' resource (current value: 10)
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: User 'badd25925bdd5f' has exceeded the 'max_user_connections' resource (current value: 10)
I tried almost everything I saw on other posts but nothing helped... I think it has to do with pooling...?
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://eu-cdbr-west-01.cleardb.com:3306/heroku_b7ea7b2d2972532?reconnect=true"/>
<property name="javax.persistence.jdbc.user" value="badd25925bdd5f"/>
<property name="javax.persistence.jdbc.password" value="XXX"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.c3p0.min_size" value="2"/>
<property name="hibernate.c3p0.max_size" value="9"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
</properties>
</persistence-unit>
</persistence>
application.conf (relevant part)
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://eu-cdbr-west-01.cleardb.com:3306/heroku_b7ea7b2d2972532"
db.default.user="badd25925bdd5f"
db.default.password="XXX"
jpa.default=defaultPersistenceUnit
Thanks a lot for your help!
I don't know about using Hibernate, but with Ebean the connection pool by default is managed by BoneCP. Try to configure it in your application.conf:
# Max connections = partitionCount * maxConnPerPartition
db.default.partitionCount=2
db.default.maxConnectionsPerPartition=5
or in your persistence.xml:
<property name="bonecp.partitionCount" value="2" />
<property name="bonecp.maxConnectionsPerPartition" value="5" />
The error says that you are using more connections then your plan .So you can
Either upgrade you db plans see https://addons.heroku.com/cleardb#ignite
or
You can try scaling down your aplication see https://devcenter.heroku.com/articles/scaling
Solution to this problem (for Play 2.3) was to add the play-hikaricp library to the application.
I write a hibernate.cfg.xml file almost the same from hibernate books like:
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.connection.password">**</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/db</property>
<property name="hibernate.connection.username">**</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="c3p0.min_size">5</property>
<property name="c3p0.max_size">30</property>
<property name="c3p0.time_out">1800</property>
<property name="c3p0.max_statement">50</property>
<!--property name="show_sql">true</property-->
<property name="format_sql"> true</property>
But this seems actually c3p0 is not used. When I do test to establish 1000 sessions, it tries to establish 1000 connections.
Could anyone please give me some hint about this?
Thank you
Looking at your configuration file seems that you are missing one key property
<property name="connection.provider_class">
org.hibernate.connection.C3P0ConnectionProvider
</property>
Try setting this property and see if this turns things around for you or not.
I'm using spring 3.0 (jdbcTemplate), Tomcat, MySQL and C3p0 to handle my database activities. I'm using both jdbctemplate and simplejdbctemplate which will take care of creating and closing connections, statements, resultsets etc. I'm using C3p0 for connection pooling however the connections are remaining open and eventually the app will run out of connections.
Here is the configuration of my data source:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" >
<property name="driverClass" value="${jdbc.driverClassName}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="initialPoolSize" value="5"></property>
<property name="maxPoolSize" value="100"/>
<property name="minPoolSize" value="5"/>
<property name="maxIdleTime" value="30"/>
<property name="maxIdleTimeExcessConnections" value="30"/>
<property name="maxConnectionAge" value="30"/>
<property name="checkoutTimeout" value="100"/>
<property name="maxStatements" value="50"></property>
<property name="automaticTestTable" value="C3P0_TEST_TABLE"></property>
<property name="testConnectionOnCheckin" value="true"></property>
<property name="idleConnectionTestPeriod" value="30"></property>
</bean>
I'm also using TransactionManagement provided by spring - here is the configuration of that:
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
Here is the rest of the datasource configuration:
<bean id="simpleJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg><ref bean="dataSource"/></constructor-arg>
</bean>
<bean id="userDAO" class="com.Test.dao.UserDAOImpl">
<property name="jdbcTemplate"><ref bean="jdbcTemplate"/></property>
</bean>
Finally here is a method where I update records into a database:
#Transactional(readOnly=false)
public void updateBenchMarkCumulative(List<BenchMarkCumulative> bmCumulativeList)
{
List<Object[]> parameters = new ArrayList<Object[]>();
for(BenchMarkCumulative bmCumulative : bmCumulativeList)
{
parameters.add(new Object[]{bmCumulative.getCumulativeAmt(), bmCumulative.getPkBenchMarkCumulative()});
}
this.simpleJdbcTemplate.batchUpdate(UPDATE_BENCHMARK_CUMULATIVE, parameters);
}
Is there something I'm doing wrong in my configuration or am I missing something that needs to be added to the configuration or coding?
Here is the exception being thrown:
INFO [http-8080-1] (AbstractPoolBackedDataSource.java510) - Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ java.beans.IntrospectionException: java.lang.reflect.InvocationTargetException [numThreadsAwaitingCheckoutDefaultUser] ]
org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
Thank you in advance.
Keith
I would agree with axtavt. I was in a similar situation, and there were couple places I was manually opening connections but not closing them (stored procedure calls for iSeries). Please verify if you have that kind of spots.