i am coming back because i still have problem using JodaTime. After the previous comments, i modified my pom and the #Type annotation is fixed. Here is my new pom :
<properties>
<org.springframework.version>3.0.3.RELEASE</org.springframework.version>
<hibernate.version>3.6.0.Beta1</hibernate.version>
</properties>
<dependencies>
...
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>20030825.184428</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>20030825.183949</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.3.1</version>
<classifier>sources</classifier>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.5</version>
</dependency>
<!-- Joda Time dependencies -->
<dependency>
<artifactId>joda-time</artifactId>
<groupId>joda-time</groupId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time-jsptags</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time-hibernate</artifactId>
<version>1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
I am actually developping a personnal project where i use Spring and Hibernate. I also use JodaTime to persist the date fields. When i am doing unit testing with Junit4, i caught this exception :
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [spring/spring-dao.xml]: Invocation of init method failed; nested exception is java.lang.IncompatibleClassChangeError: Implementing class
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
....
fr.cc2i.intervention.dao.test.WebInterventionTest.oneTimedSetUp(WebInterventionTest.java:33)
.....
Caused by: java.lang.IncompatibleClassChangeError: Implementing class
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
at java.lang.Class.getConstructor0(Class.java:2699)
at java.lang.Class.getDeclaredConstructor(Class.java:1985)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:104)
at
.....
According to that website : http://www.mail-archive.com/joda-interest#lists.sourceforge.net/msg00609.html, jodatime might cause the error.
Can someone explain me what is : java.lang.incompatibleChangeError : Implementing Class ?
and how to solve that problem?
My spring configuration :
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource"> <ref local="dataSource" /></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
<!-- Pour les requetes SQL -->
<prop key="hibernate.query.substitutions">true 1, false 0, yes 'Y', no 'N'</prop>
<!-- manipuler avec attention -->
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>fr.cc2i.intervention.dao.beans.Client</value>
<value>fr.cc2i.intervention.dao.beans.Intervention</value>
<value>fr.cc2i.intervention.dao.beans.Technicien</value>
<value>fr.cc2i.intervention.dao.beans.Contrat</value>
</list>
</property>
</bean>
My entity class :
package fr.cc2i.intervention.dao.beans;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.joda.time.Period;
/**
* Classe définissant un contrat
* My code is written in French ;)
* #author lindows
*
*/
#Entity
#Table(name="T_Contrat")
public class Contrat {
private long id;
private String reference;
private Period heures_totales;
private Period heures_restantes;
public Contrat(){}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public long getId() {
return id;
}
private void setId(long id) {
this.id = id;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
#Column
#Type(type="org.joda.time.contrib.hibernate.PersistantPeriod")
public Period getHeures_totales() {
return heures_totales;
}
public void setHeures_totales(Period heuresTotales) {
heures_totales = heuresTotales;
}
#Column
#Type(type="org.joda.time.contrib.hibernate.PersistantPeriod")
public Period getHeures_restantes() {
return heures_restantes;
}
public void setHeures_restantes(Period heuresRestantes) {
heures_restantes = heuresRestantes;
}
public String toString(){
return this.reference + " - \n Heures totales :" + this.heures_totales.toString() +
" Heures Restantes : " + this.heures_restantes.toString();
}
}
Thanks for your help
As I wrote in a comment, your pom.xml is messy and this is somehow the root cause of the issue. Here comes the full explanation.
According to the announcement of the Simultaneous Hibernate 3.5.4 and 3.6.0.Beta1 Releases quoted below, the hibernate-annotations module has been merged into core in Hibernate 3.6.x (made possible since Hibernate 3.6.x is dropping JDK 1.4 support):
3.6.0.Beta1
3.6 introduces some new features as well as incorporating most of the
fixes from 3.5. Changes of particular
interest include
Dropping support for JDK 1.4
merging some modules into core; specifically hibernate-jmx and
hibernate-annotations
repackaging of classes in hibernate-testing
HHH-2277 : fixes a long known limitation in key-many-to-one support.
HHH-5138, HHH-5182, HHH-5262 : collectively address a
number of improvements to the
"Hibernate type system". See the newly
separated and expanded chapter on
Types in the reference manual for
details.
HHH-5268 : java.util.UUID support
For more details about 3.6.0.Beta1,
including the full list of changes,
see the release page.
And indeed, the latest versions of hibernate-annotations-3.6-SNAPSHOT.jar are actually empty jars (because of the merge) that were temporarily built until the total removal of the maven module itself. But because you're not using hibernate-core-3.6-SNAPSHOT.jar, you just don't have the #Type annotation at all.
Now, here is a summary of my recommendations/remarks:
Use Maven transitive dependency resolution mechanism, do not declare all dependencies but only the "top level" one i.e. hibernate-entitymanager if you want to use JPA.
Starting with version 3.5, Hibernate Core, Annotations, EntityManager are released together, their versions are in sync.
If you want to use Hibernate 3.6.x (Beta2 is there now), the #Type is in hibernate-core (that's not really important if you use transitive dependencies).
I don't recommend to rely on SNAPSHOT unless you know exactly what you're doing.
So your pom.xml should declare something like this for Hibernate:
<project>
...
<properties>
<!--hibernate.version>3.4.O.GA</hibernate.version--> <!-- for JPA 1.0 -->
<hibernate.version>3.5.4-Final</hibernate.version> <!-- for JPA 2.0 -->
<!--hibernate.version>3.6.0.Beta2</hibernate.version--> <!-- experimental -->
<properties>
...
<dependencies>
<!-- Hibernate dependencies -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
...
</dependencies>
...
</project>
And that's all you need.
The #Type annotation is present in hibernate-annotations, version 3.5.1-Final. I don't find the snapshot you are using 3.6.0-SNAPSHOT in the jboss repository, so I couldn't test that specifically, but my guess is that the annotation is missing/has been removed from the snapshot version for some reason.
Unless there is a specific reason you need a snapshot, I would stick to released versions. If you revert to 3.5.1-Final, that will fix the problem.
The Type API is changing in Hibernate 3.6.0. I would be surprised if the Joda Time Contrib classes work at all with Hibernate 3.6 although they should work with Hibernate 3.5. Can I suggest you take a look at my project which has implementations of Usertypes for Joda Time and JSR310: http://usertype.sourceforge.net/
Thanks and regards,
Chris
Related
I have an application with Hibernate 5, and added JPA 2.1 to perform bulk Updates with CriteriaBuilder.createCriteriaUpdate().
But I need to assign CriteriaBuilder from EntityManager.getCriteriaBuilder(), and I can't get the EntityManager.
I don't have a persistence.xml file, and I thought Hibernate would provide an EntityManager for me.
I tried the following annotations in the DAO class:
#Autowired
EntityManager entityManager
and
#PersistenceContext
EntityManager entityManager;
Both fail to inject the dependency.
I also tried to instace an EntityManagerFactory, but it failed as I don't have a persistence.xml file. All the entities are annotated like this:
#Entity
#Table(name = "My_Entity")
public class MyEntity extends BaseEntity {
private static final long serialVersionUID = -8442071276091708080L;
#Column(name = "VALUE", nullable = false)
private BigDecimal value;
...
}
Here is part of my pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.1.3.Final</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.3.Final</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
applicationContext.xml
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="nestedTransactionAllowed" value="true"/>
</bean>
Hibernate instances the SessionFactory, is there a way to get the EM from it?
If you use spring it would be much easier to use the spring boot starters modules. For JPA it would be "spring-boot-starter-data-jpa" you can find the definition of the maven dependency here.
Additionally, could you add more information about your configuration? You say you don't use a persistence.xml so what do you use to set your datasources?
I am getting this error:
Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named tarefas at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
My jars is okay, as you seem in the pom.xml
My main class:
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class GeraTabelas {
public static void main(String[] args)
{
EntityManagerFactory factory = Persistence.createEntityManagerFactory("tarefas");
factory.close();
}
}
pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.9.Final</version>
</dependency>
persistence.xml
<persistence-unit name="tarefas">
<!-- provedor/implementacao do JPA -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- entidade mapeada -->
<class>br.com.abc.models.Usuario</class>
<properties>
<property name="hibernate.connection.url" value= .... //The rest of properties...
</properties>
</persistence-unit>
It may be the position of the pom.xml file in the wrong location? I did this way because of others posts that said it was this way but this interrogation point appears in the folders and I am beginner in Maven to know what it is.
Thanks.
I have a made a sample application in Spring + Hibernate + ZK framework.
In the Hibernate configuration file I have kept the property hbm2ddl.auto in "update" mode. Still Whenever I run the application again I dont get the values persisted earlier.
Following are several configuration files for reference:
BeanLocations.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Database Configuration -->
<import resource="../database/DataSource.xml"/>
<import resource="../database/Hibernate.xml"/>
<!-- Auto scan the components -->
<context:component-scan
base-package="com.nagarro" />
</beans>
DataSource.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>properties/database.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- <property name="hibernate.current_session_context_class" value = "${hibernate.current_session_context_class}" /> -->
</bean>
</beans>
Hibernate.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">
<!-- Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.nagarro.model.ItemAttribute</value>
<value>com.nagarro.model.ItemAttributeGroup</value>
</list>
</property>
</bean>
</beans>
Controller/ Viewmodel class
public class ItemAttributeRenderer {
/*
* The Logger reference variable used for Logging.
*/
static private final Logger LOG = LoggerFactory.getLogger(ItemAttributeRenderer.class);
#Autowired
private ItemAttributeService itemAttrService;
private List<ItemAttribute> itemList = new ArrayList<ItemAttribute>();
private void prepareAndSaveItemAttributeData(){
ItemAttribute item = null;
int counter;
for(int index = 0; index < 5; index++){
counter = index+1;
item = new ItemAttribute("Item "+counter, "Attirbute Value"+counter, "Qualifier Value"+counter);
itemAttrService.save(item);
}
}
/**
* #return the itemList
*/
public List<ItemAttribute> getItemList() {
ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring/config/BeanLocations.xml");
itemAttrService = (ItemAttributeService)appContext.getBean("itemAttrService");
prepareAndSaveItemAttributeData();
itemList = itemAttrService.getItemAttributeList();
return itemList;
}
#Command
public void save(){
for(ItemAttribute item : itemList){
itemAttrService.update(item);
}
}
/**
* #param itemList the itemList to set
*/
public void setItemList(List<ItemAttribute> itemList) {
this.itemList = itemList;
}
/**
* #return the itemAttrService
*/
public ItemAttributeService getItemAttrService() {
return itemAttrService;
}
/**
* #param itemAttrService the itemAttrService to set
*/
public void setItemAttrService(ItemAttributeService itemAttrService) {
this.itemAttrService = itemAttrService;
}
}
View file:
<?page title="Result"?>
<zk>
<custom-attributes center="${arg.center }" />
<window apply="org.zkoss.bind.BindComposer"
viewModel="#id('vm') #init('com.nagarro.viewmodel.ItemAttributeRenderer')"
title="Result Window" border="normal">
<div>
<grid>
<rows>
<row>
<listbox model="#bind(vm.itemList)">
<listhead>
<listheader label="Item Name"
style="text-align:center;">
</listheader>
<listheader label="Attribute Value"
style="text-align:center;">
</listheader>
<listheader label="Qualifier Value"
style="text-align:center;">
</listheader>
</listhead>
<template name="model" var="item">
<listitem value="${item }">
<listcell label="#load(item.name)"
style="text-align:center;">
</listcell>
<listcell style="text-align:center;">
<textbox value="#bind(item.attributeValue)"
style="text-align:center;"/>
</listcell>
<listcell
label="#load(item.qualifierValue)"
style="text-align:center;">
</listcell>
</listitem>
</template>
</listbox>
</row>
</rows>
</grid>
</div>
<div style="text-align:right; padding:10px;">
<button label="Save" mold="trendy"
onClick="#command('save')">
</button>
</div>
</window>
</zk>
Service class
#Service("itemAttrService")
public class ItemAttributeServiceImpl implements ItemAttributeService{
#Autowired
ItemAttributeDao itemAttrDao;
public void setItemAttrDao(ItemAttributeDao itemAttrDao) {
this.itemAttrDao = itemAttrDao;
}
public void save(ItemAttribute item){
itemAttrDao.save(item);
}
public void update(ItemAttribute item){
itemAttrDao.update(item);
}
public void delete(ItemAttribute item){
itemAttrDao.delete(item);
}
public ItemAttribute findByItemAttributeName(String name){
return itemAttrDao.findByItemAttributeName(name);
}
public List<ItemAttribute> getItemAttributeList(){
return itemAttrDao.getItemAttributeList();
}
}
DAO class
#Repository("itemAttrDao")
public class ItemAttributeDaoImpl extends CustomHibernateDaoSupport implements ItemAttributeDao {
public void save(ItemAttribute itemAttribute) {
getHibernateTemplate().save(itemAttribute);
//getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
}
public void update(ItemAttribute itemAttribute) {
getHibernateTemplate().update(itemAttribute);
//getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
}
public void delete(ItemAttribute itemAttribute) {
getHibernateTemplate().delete(itemAttribute);
//getHibernateTemplate().getSessionFactory().getCurrentSession().getTransaction().commit();
}
public ItemAttribute findByItemAttributeName(String name) {
List list = getHibernateTemplate().find("from ItemAttribute where name=?",name);
if(list == null){
}else if(list.isEmpty()){
}
return (ItemAttribute)list.get(0);
}
public List<ItemAttribute> getItemAttributeList() {
List<ItemAttribute> itemList = getHibernateTemplate().find("from ItemAttribute ");
return itemList;
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.abc</groupId>
<artifactId>ZKSpringHibernateExample</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringHibernateExample</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>java.net</id>
<url>http://download.java.net/maven/2/</url>
</repository>
</repositories>
<properties>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- MySQL database driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<!-- Hibernate framework -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- Hibernate library dependecy start -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<!-- Hibernate library dependecy end -->
<!-- ZK Dependency start -->
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkplus</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zhtml</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkbind</artifactId>
<version>6.0.0</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zul</artifactId>
<version>6.0.0</version>
</dependency>
<!-- ZK Dependency Ends -->
</dependencies>
</project>
My problem is When I run the application again all the data that was saved earlier vanishes even though I have set the hbm2ddl.auto property to update mode.
I have set my show_sql property as "true" to check the queries that are getting fired but there are no delete queries which are getting fired.
Is there any other important thing that I am missing here.
See comments and read Hibernate manual here
<property name="hbm2ddl.auto">update</property>
setting above property Drop and re-create the database schema on startup
consider below comments from hibernate manual.
Hibernate's automatic session management for persistence contexts is particularly useful in this context. The hbm2ddl.auto option turns on automatic generation of database schemas directly into the database. This can also be turned off by removing the configuration option, or redirected to a file with the help of the SchemaExport Ant task.
hbm2ddl.auto is for the validation of the database schema, which doesn't have any meaning here.
You have to commit your values, if not they are not permanently stored in the database.
I found the solution. there were a lot of messy project dependencies in my Tomcat so I deleted that instance of Tomcat and reconfigured it for my project. Then I cleaned my project and now everything is working fine as it should be. Thanks for taking time to post the answers.
I have created very simple app with persistence context (hibernate as provider) to read some value from database. I use Eclipse with Maven.
First, I get
Caused by: org.apache.openejb.OpenEJBException: java.lang.ClassCastException: org.hibernate.ejb.HibernatePersistence cannot be cast to javax.persistence.spi.PersistenceProvider:
and according to this topic
http://openejb.979440.n4.nabble.com/problem-with-hibernate-persistence-provider-td980429.html
I excluded hibernate-jpa-2.0-api. Now, my dependencies look
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.3.Final</version>
<exclusions>
<exclusion>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
</exclusion>
</exclusions>
</dependency>
Now, I don't know why...
Caused by: java.lang.ClassNotFoundException: org.hibernate.transaction.TransactionManagerLookup
But TransactionManagerLookup is in hibernate-core.
Please, can anybody tell me, how should look pom.xml to use hibernate in TomEE?
1. Copy the required Hibernate .jars to <tomee-home>/lib
According to the documentation ( http://tomee.apache.org/tomee-and-hibernate.html ), the following ones are sufficient and in fact they worked for me:
<tomee-home>/lib/antlr-2.7.7.jar
<tomee-home>/lib/dom4j-1.6.1.jar
<tomee-home>/lib/hibernate-commons-annotations-4.0.2.Final.jar
<tomee-home>/lib/hibernate-core-4.2.21.Final.jar
<tomee-home>/lib/hibernate-entitymanager-4.2.21.Final.jar
<tomee-home>/lib/hibernate-validator-4.3.2.Final.jar
<tomee-home>/lib/javassist-3.18.1-GA.jar
<tomee-home>/lib/jboss-logging-3.1.0.GA.jar
All these .jars are contained in the Hibernate ORM 4.2.x download ( http://hibernate.org/orm/ ), except for the Hibernate Validator, which is a separate download ( http://hibernate.org/validator/ ).
2. Edit your pom.xml
Using the javaee-api maven artifact with a scope of provided you can now use the JPA specification in your project. However, if you have been using some Hibernate specific features, classes or annotations before, you can still refer to Hibernate in your pom.xml to match those dependencies:
<!-- JPA spec (required) -->
<dependencies>
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0-4</version>
<scope>provided</scope>
</dependency>
<!-- Hibernate specific features (only if needed) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.21.Final</version>
<scope>provided</scope>
</dependency>
3. Define your database connection
Edit <tomee-home>/conf/tomee.xml:
<Resource id="myJtaDatabase" type="DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/my_dbname?autoReconnect=true
UserName foo
Password bar
validationQuery = SELECT 1
JtaManaged true
</Resource>
You can also put the above <Resource>...</Resource> definition into WEB-INF/resources.xml and ship it with your application instead:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<!-- Put <Resource> elements here -->
<resources>
4. JTA Datasource
Now that you told TomEE how to establish a connection, define a JTA datasource in /src/main/java/META-INF/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="my_persistence_unit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:openejb/Resource/myJtaDatabase</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<!-- As many hibernate properties as you need, some examples: -->
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<!-- Drop and then re-create the database schema (don't do this in production) -->
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
5. Start using JPA
Obtain an EntityManager in a CDI bean or EJB like this:
#PersistenceContext(unitName = "my_persistence_unit")
private EntityManager em;
Final Notes
Hibernate versions 4.3+
I am using Hibernate 4.2.21 (JPA 2.0, Java EE 6) along with TomEE 1.7.2. Any TomEE 1.7.x, 1.6.x and 1.5.x will work. However, you cannot use Hibernate 4.3+ (JPA 2.1 / Java EE 7), as TomEE 1.7.x and below only support Java EE 6. If you really want to use Java EE 7 features along with TomEE, this blog post might be helpful: http://rmannibucau.wordpress.com/2013/07/19/little-tip-to-help-you-to-test-javaee-7-in-tomee-with-tomee-maven-plugin/
TomEE 1.5.x
TomEE 1.5.x already includes a javassist-<version>.jar, so you don't have to copy one.
Try this:
Add:
<tomee-home>/lib/antlr-2.7.7.jar
<tomee-home>/lib/dom4j-1.6.1.jar
<tomee-home>/lib/ehcache-core-2.5.1.jar
<tomee-home>/lib/ehcache-terracotta-2.5.1.jar
<tomee-home>/lib/hibernate-commons-annotations-4.0.1.Final.jar
<tomee-home>/lib/hibernate-core-4.1.4.Final.jar
<tomee-home>/lib/hibernate-ehcache-4.1.4.Final.jar
<tomee-home>/lib/hibernate-entitymanager-4.1.4.Final.jar
<tomee-home>/lib/hibernate-validator-4.3.0.Final.jar
<tomee-home>/lib/jboss-logging-3.1.0.GA.jar
<tomee-home>/lib/terracotta-toolkit-1.4-runtime-4.1.0.jar
The ehcache jars might be optional, but haven't tried without them.
Remove (optional):
<tomee-home>/lib/asm-3.2.jar
<tomee-home>/lib/bval-core-0.4.jar
<tomee-home>/lib/bval-jsr303-0.4.jar
<tomee-home>/lib/commons-lang-2.6.jar
<tomee-home>/lib/openjpa-2.2.0.jar
<tomee-home>/lib/serp-1.13.1.jar
yes just dropping the hibernate-jpa-2.1-api-1.0.0.Final.jar into the TomEE lib folder worked for me.
I have some problems getting the hibernate second level cache to work for caching domain objects. According to the ehcache documentation it shouldn't be too complicated to add caching to my existing working application.
I have the following setup (only relevant snippets are outlined):
#Entity
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE
public void Entity {
// ...
}
ehcache-entity.xml
<cache name="com.company.Entity" eternal="false"
maxElementsInMemory="10000" overflowToDisk="true" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU" />
ApplicationContext.xml
<bean class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="ds" />
<property name="annotatedClasses">
<list>
<value>com.company.Entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="net.sf.ehcache.configurationResourceName">/ehcache-entity.xml</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</prop>
....
</property>
</bean>
Maven dependencies
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.4.0.GA</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-hibernate3</artifactId>
<version>2.0.8</version>
<exclusions>
<exclusion>
<artifactId>hibernate</artifactId>
<groupId>org.hibernate</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.3.2</version>
</dependency>
A test class is used which enables cache statistics:
Cache cache = cacheManager.getCache("com.company.Entity");
cache.setStatisticsAccuracy(Statistics.STATISTICS_ACCURACY_GUARANTEED);
cache.setStatisticsEnabled(true);
// store, read etc ...
cache.getStatistics().getMemoryStoreObjectCount(); // returns 0
No operation seems to trigger any cache changes. What am I missing? Currently I'm using HibernateTemplate in the DAO, perhaps that has some impact.
[EDIT]
The only ehcache log output when set to DEBUG is:
SettingsFactory: Cache region factory : net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory
Do you need to manually tell Hibernate to use the EHCache provider? I've never really been sure if this is required, but Hibernate does support a number of cache providers so I suspect that it might be necessary to explicitly tell Hibernate which one you want. Try adding this property to ApplicationContext.xml:
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
There were several causes that I've identified:
Correct maven dependencies:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.1</version>
</dependency>
Added the #Cacheable annotation from javax.persistence to my entities.
Read logging from hibernate instead of ehcache.
getSessionFactory().getStatistics().logSummary();
Not all hibernate operations seems to affect the cache. This I need to read up on further.
By looking at your config, it all seems fine afaict. Only thing worth noticing, is that when using the HibernateTemplate, you have to explicitly setCacheQueries(true) if you plan on using the query cache... Which I wouldn't recommend, except if you really need it: http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/orm/hibernate3/HibernateTemplate.html#setCacheQueries(boolean)
Did you try the Hibernate statistics instead of the Ehcache ones ? Do you get cache misses there ? (reason I ask is to be sure you do use the same CacheManager as Hibernate does)...
you can reference following configure
<prop key="hibernate.cache.use_query_cache">true</prop>
In hibernate.cfg.xml add:
<hibernate-configuration>
<session-factory>
...
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_query_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>