I am trying to use HikariCP with Hibernate in a maven java ee web app in Netbeans. This is my first time using Hibernate, and I am not using Spring yet as I am not familiar with it but may consider it in the future (please feel free to offer reason why I should adapt it).
In the HikariCP wiki, it mentions that:
As of Hibernate 4.3.6 there is an official ConnectionProvider class
from Hibernate, which should be used instead of the HikariCP
implementation. The class is called
org.hibernate.hikaricp.internal.HikariCPConnectionProvider.
It then goes on to describe the configuration for Hibernate 4.x. It talks about the old ConnectionProvider class there however so I am assuming this section is outdated?
I have added the following dependency to my POM.XML file:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-hikaricp</artifactId>
<version>4.3.8.Final</version>
</dependency>
and with the following properties declared within the tag in hibernate.cfg.xml:
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</property>
<property name="hibernate.hikari.dataSource.url">jdbc:mysql://localhost/testdb?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.hikari.dataSource.user">testuser</property>
<property name="hibernate.hikari.dataSource.password">password</property>
<property name="hibernate.hikari.dataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlDataSource</property>
<property name="hibernate.hikari.dataSource.cachePrepStmts">true</property>
<property name="hibernate.hikari.dataSource.prepStmtCacheSize">250</property>
<property name="hibernate.hikari.dataSource.prepStmtCacheSqlLimit">2048</property>
<property name="hibernate.hikari.dataSource.useServerPrepStmts">true</property>
<property name="hibernate.current_session_context_class">thread</property>
I am able to interact with the database as I was before, using the default Hibernate connection pool. Is this all I need to do? Is it now using the HikariCP connection pool? If not what other configuration is required?
If I were to later integrate Spring, how would this affect the HikariCP configuration, or location of the configuration?
Related
I tried to write some code with EntityManager but hibernate was updated to hibernate-core(6.0.0.Final) and with new hibernate 6.0 my old codes doesn't work
There my code:
my pom.xml
enter image description here
my persistence.xml file
<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="CRM">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5678/postgres"/>
<property name="hibernate.connection.username" value="postgres"/>
<property name="hibernate.connection.password" value="postgres"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
and my main method
EntityManagerFactory entityManagerFactory =
Persistence.createEntityManagerFactory("CRM");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
entityManager.persist(new SuperHero());
entityManager.getTransaction().commit();
entityManager.close();
entityManagerFactory.close();
here result
enter image description here
thanks in advance for your help
It looks as if you are mixing 2 incompatible versions of Hibernate resources:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Final</version>
</dependency>
and:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.6.7.Final</version>
</dependency>
From v6 onwards, the Hibernate libraries have moved from using Java Persistence to Jakarta Persistence. You can read about this larger Java ecosystem change elsewhere Transition from Java EE to Jakarta EE - and also in other SO questions and answers.
By including a Hibernate Entity Manager v5 dependency, your project will still be referring to a Java Persistence library (e.g. via javax.persistence-api-2.2.jar or similar). This means your code may still compile - but, as you see, it will not execute. You will see error messages referring to javax classes, which are no longer supported by the v6 Hibernate Core library.
Furthermore, Hibernate's JPA support has been merged into the hibernate-core module, making the hibernate-entitymanager module obsolete. You can see a note about this by looking at the readme.txt file in your Entity Manager 5.6.7 JAR file:
Hibernate's JPA support has been merged into the hibernate-core module, making this hibernate-entitymanager module obsolete. This module will be removed in Hibernate ORM 6.0.
Recommended steps:
Remove the hibernate-entitymanager dependency from your POM. That will probably trigger a series of compilation errors, because you will no longer have any library support for classes such as javax.persistence.EntityManager.
Update all your javax imports to jakarta imports. So, for example, taking the class from (1) above, that becomes:
import jakarta.persistence.EntityManager;
In your persistence.xml file you will also need to fix any similar references to javax - for example:
<property name="jakarta.persistence.jdbc.driver"
value="com.mysql.jdbc.Driver" />
Final Notes
If you still face issues following the above steps, then you can refer to the official Hibernate ORM 6.0 Migration Guide.
I am trying to configure C3P0 connection pool for my hibernate application.
I am using below dependencies.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.5.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.5.6.Final</version>
</dependency>
I added below configs in my hibernate.cft.xml
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.acquire_increment">5</property>
<property name="hibernate.c3p0.timeout">1800</property>
But I get the warning below:
WARN: HHH000022: c3p0 properties were encountered, but the c3p0 provider class was not found on the classpath; these properties are going to be ignored
If I explicitly specify the provider class like given below, it works.
<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
But the documentation of the above class says it should be picked by default.
A connection provider that uses a C3P0 connection pool. Hibernate will
use this by default if the hibernate.c3p0.* properties are set.
Why is this not class picked up by default? Is it correct to explicitly specify org.hibernate.c3p0.internal.C3P0ConnectionProvider? It looks like org.hibernate.connection.C3P0ConnectionProvider is the class which is picked up by default, and most of the references found in the web are regarding it, but it is not available in the above mentioned maven dependencies.
Remove hibernate. from the property name, it should be:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
When I debug my Mule application i have error:
org.springframework.dao.DataAccessResourceFailureException: Error retrieving database metadata; nested exception is org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: No suitable driver found for jdbc:h2:~/test
my java code:
SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate.getDataSource()).withProcedureName("my_procedure_name").withSchemaName("my_schema");
...
call.execute(in)
my aaplicationContext:
<bean id="dataSource2"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db2.driver}" />
<property name="url" value="${db2.url}" />
<property name="username" value="${db2.user}" />
<property name="password" value="${db2.password}" />
</bean>
my app_name.properties:
db2.url=jdbc:h2:~/test
db2.driver=org.h2.Driver
db2.user=sa
db2.password=
my pom:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
my classpath:
<classpathentry kind="var" path="M2_REPO/com/h2database/h2/1.4.200/h2-1.4.200.jar"/>
log info after run application:
INFO org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: org.h2.Driver
Also i put h2-1.4.200.jar (when I starting my application from AnypointStudio) to:
c:\...\plugins\org.mule.tooling.server.3.9.0_6.4.0.201908221250\mule\lib\user\
and:
c:\...\plugins\org.mule.tooling.server.3.9.0_6.4.0.201908221250\mule\lib\boot\
and:
c:\...\plugins\org.mule.tooling.server.3.9.0_6.4.0.201908221250\mule\lib\mule\
and when I run application from mule server h2-1.4.200.jar, I put here:
..\mule-standalone-3.9.0\lib\boot
and
..\mule-standalone-3.9.0\lib\user
and:
..\mule-standalone-3.9.0\lib\mule
why application driver h2 not found ? what's the problem ?
Thanks.
You are mixing 3 different ways of managing the JDBC driver dependency, and also duplicating the library in the runtimes. That also makes it more difficult to understand the problem, and to deploy an application.
Let's start with Maven. It looks like you are using the right dependency in the pom, as long as it is in the section.
If the project is using Maven, there should not be any need to look into , unless it is out of sync with Maven. You should not change the class path manually, or edit the build path in Anypoint Studio. These are part of Studio/Eclipse .classpath files and should be left alone. Be sure to update the project so Studio regenerates the classpath.
About MULE_HOME\lib\boot, MULE_HOME\lib\user, MULE_HOME\lib\mule (either in Studio or standalone), you should not put the library in there. The Maven dependency is enough and you are duplicating the versions. Even if you can share a library in lib\user, it is not recommended. It makes more difficult to replicate sanely a deployment and again, there is no need for the JDBC driver. You should not put anything at all in lib\boot nor lib\mule nor the other subdirectories of lib. These are reserved for the runtime.
Try removing all those extras first and see what happens with a clean deployment.
Update:
Once the libraries are cleaned up, take into account that the Spring class may have some classloading issues itself. It is almost always better to use a datasource pool implementation. There are several to choose, like c3p0, dbcp, and others.
One example with c3p0:
<spring:bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<spring:property name="driverClass" value="${JDBC.driver}"/>
<spring:property name="jdbcUrl" value="${JDBC.URL}"/>
<spring:property name="user" value="${JDBC.user}"/>
<spring:property name="password" value="${JDBC.password}"/>
<spring:property name="minPoolSize" value="5"/>
<spring:property name="maxPoolSize" value="20"/>
</spring:bean>
See https://help.mulesoft.com/s/article/Spring-based-datasources for more examples.
I have a Java EE application which uses Hibernate 4.2.7 as persistence provider executing Junit tests in an embeddable Websphere 8.0.0 container. Database access works fine in a real (i.e. non-embedded) Websphere 8.0.0 instance. The unit tests do work when run with OpenJPA instead of Hibernate. However, running the Junit tests with Hibernate, I get the following exception:
CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method "getEntity" on bean "BeanId(embeddable#classes#SomeBean, null)". Exception data: org.hibernate.service.jndi.JndiException: Unable to lookup JNDI name [java:comp/websphere/ExtendedJTATransaction]
at org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:68)
at org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform$TransactionManagerAdapter$TransactionAdapter.(WebSphereExtendedJtaPlatform.java:156)
at org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform$TransactionManagerAdapter$TransactionAdapter.(WebSphereExtendedJtaPlatform.java:152)
at org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform$TransactionManagerAdapter.getTransaction(WebSphereExtendedJtaPlatform.java:124)
at org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform$TransactionManagerAdapter.getStatus(WebSphereExtendedJtaPlatform.java:119)
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:73)
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:115)
at org.hibernate.service.jta.platform.internal.TransactionManagerBasedSynchronizationStrategy.canRegisterSynchronization(TransactionManagerBasedSynchronizationStrategy.java:56)
... stripped ...
It seems the implementation of WebsphereExtendedJtaPlatform is trying to get the current transaction via a JNDI lookup but fails because that JNDI name does not exist in the embedded container. Here's a snipped from org.hibernate.service.jta.platform.internal.WebsphereExtendedJtaPlatform:
public class TransactionAdapter implements Transaction {
private TransactionAdapter() {
if ( extendedJTATransaction == null ) {
extendedJTATransaction = jndiService().locate( "java:comp/websphere/ExtendedJTATransaction" );
}
}
... stripped ...
The class ExtendedJtaTransaction itself does exist on the class path inside com.ibm.ws.runtime.jar.
The settings in our persistence.xml look like this:
<persistence-unit name="BLA" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/BLA</jta-data-source>
<class>com.some.Entity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WebSphereExtendedJTATransactionLookup" />
<property name="jta.UserTransaction" value="java:comp/UserTransaction" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.jdbc.fetch_size" value="100" />
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false" />
</properties>
Does anyone have a solution for this?
Thanks!
Transaction strategy configuration
Hibernate requires the configuration of two essential pieces in order to properly run with transactions. The first, hibernate.transaction.factory_class, defines transactional control and the second, hibernate.transaction.manager_lookup_class, defines the mechanism for registration of transaction synchronization so the persistence manager is notified at transaction end when it needs to synchronize changes with the database. For transactional control, both container-managed and bean-managed configurations are supported. The following properties must be set in Hibernate.cfg.xml when using Hibernate with WebSphere Application Server:
for container-managed transactions:
<property name="hibernate.transaction.factory_class">
org.hibernate.transaction.CMTTransactionFactory
</property>
<property name="hibernate.transaction.manager_lookup_class">
org.hibernate.transaction.WebSphereExtendedJTATransactionLookup
</property>
for bean-managed transactions:
<property name="hibernate.transaction.factory_class">
org.hibernate.transaction.JTATransactionFactory
</property>
<property name="hibernate.transaction.manager_lookup_class">
org.hibernate.transaction.WebSphereExtendedJTATransactionLookup
</property>
<property name="jta.UserTransaction">
java:comp/UserTransaction
</property >
The jta.UserTransaction property configures the factory class to obtain an instance of a UserTransaction object instance from the WebSphere container.
The hibernate.transaction.manager_lookup_class property is supported on the WebSphere platform by WebSphere Application Server V6.x and later, and on WebSphere Business Integration Server Foundation V5.1 and later. This property configures Hibernate to use the ExtendedJTATransaction interface, which was introduced in WebSphere Business Integration Server Foundation V5.1 and WebSphere Application Server V6.0. The WebSphere ExtendedJTATransaction interface establishes a pattern that is formalized in Java EE 5 via the JTA 1.1 specification.
This was working:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
...
but upgrading to the aforementioned versions breaks it. What is the correct method to create a SessionFactory bean with Spring 3.1.Release and Hibernate 4.0.0.FINAL?
The error on deploy is:
nested exception is java.lang.NoClassDefFoundError:
Lorg/hibernate/cache/CacheProvider;
EDIT
Have added my own answer, which fixed it for me.
I think you should use org.springframework.orm.hibernate4.LocalSessionFactoryBean instead of
org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
From LocalSessionFactoryBean javadoc:
NOTE: This variant of LocalSessionFactoryBean requires Hibernate 4.0 or higher. It is similar in role to the same-named class in the orm.hibernate3 package. However, in practice, it is closer to AnnotationSessionFactoryBean since its core purpose is to bootstrap a SessionFactory from annotation scanning.
Hibernate 4 has removed the deprecated CacheProvider-related interfaces and classes in favor of the previously released RegionFactory-related cache interface. You can find the version 4 cache package summary here, the version 3.2 cache package summary here (just before the RegionFactory interface was added) and the version 3.3 cache package summary here (when RegionFactory was first released).
Other than the JavaDoc, you might find the following documentation useful:
Using JBoss Cache as a Hibernate Second Level Cache - Chapter 5. Architecture
Ehcache Hibernate Second-Level Cache
Hibernate 4 - The Second Level Cache
However, based on the Spring 3.1 dependencies Spring 3.1 does not require Hibernate 4 (under the Full Dependencies section, JBoss Hibernate Object-Relational Mapper is at version 3.3.2.GA). If you want to upgrade to Hibernate 4, you'll need to update your cache settings. Otherwise, try using Hibernate 3.3.2 or higher 3.X version instead.
UPDATE: Keep in mind, Hibernate 4 documentation in Spring 3.1 is currently sparse. The Spring Framework Reference Documentation only has the following for Support for Hibernate 4.x:
See Javadoc for classes within the new org.springframework.orm.hibernate4 package
Spring 3.1 introduces the LocalSessionFactoryBuilder, which extends Hibernate's Configuration.
It would seem you should keep an eye out for some other changes if you want to use Hibernate 4.
UPDATE 2: Just noticed this question is a close duplicate of Exception NoClassDefFoundError for CacheProvider.
Use this configuration
hibernate configuration file:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
POM:
<!-- CGLIB -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>${cglib-version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${org.hibernate-version}</version>
<!-- will come with Hibernate core -->
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
i forgot to include the versions, I am using hibernate version: 4.1.2.Final and spring version: 3.1.1.RELEASE, there is an update of hibernate 4.1.3.Final, not tested but I believe it will work fine.
I had to change a couple of things, here we go :
In my transaction manager set up changed 3 -> 4 :
org.springframework.orm.hibernate4.HibernateTransactionManager;
And my sessionFactory to this (thanks #toxin) :
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
In the case of Hibernate 4.0 or higher, as of Spring 4.0, you should use
org.springframework.orm.hibernate4.LocalSessionFactoryBean
For example:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
...
</bean>
See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/orm/hibernate4/LocalSessionFactoryBean.html
In the case of Hibernate 5.0/5.1/5.2, as of Spring 4.3, you should better instead use
org.springframework.orm.hibernate5.LocalSessionFactoryBean
(See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/orm/hibernate5/LocalSessionFactoryBean.html)
Spring 3.1 and Hibernate 4 are not compatible in so many ways. Please refer the following Spring JIRA https://jira.springsource.org/browse/SPR-9365