Unit Testing DAO fails on persist with hsqldb and hibernate - java

So i've been at this problem all day and I still can't work it out. This works if i run it in jboss 7 with mysql. I created a test persistence.xml which differs from my production one by connection properties and doesn't use jndi.
I am trying to get this code to run locally but I am having problems, I am getting a PropertyAccessException when I try and persist a User entity using em.persist(myUser) the stack trace shows that hibernate is trying to set User.id which is of type long to the (or a) User Object.
I dont understand why this is happening, could you please explain why hibernate is confused.
The pom contains all of the application dependencies most are probably irrelevant but I thought i may also have a duplicate package somewhere.
I also looked for some details about what versions of these dependencies are used in jboss as 7.1.1.Final but not much luck
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="testing" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>mypackage.beans.User</class>
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:mem:test"/>
<property name="hibernate.showSql" value="true"/>
<property name="hibernate.archive.autodetection" value="true"/>
</properties>
</persistence-unit>
</persistence>
Entity
#Entity
#Table(name = "REPORTER")
public class User{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "REPORTER_ID", nullable = false, unique = true)
private long id;
#Column(name = "REPORTER_USERNAME", nullable = false, unique = true)
private String username;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username){
this.username = username;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (id != user.id) return false;
if (!username.equals(user.username)) return false;
return true;
}
#Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + username.hashCode();
return result;
}
}
pom
<dependencies>
<!-- resteay core library -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.3.2.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.3.2.Final</version>
<scope>provided</scope>
</dependency>
<!--Shiro Security Framework-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.2</version>
</dependency>
<!--joda time libs-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.2</version>
</dependency>
<!-- twitter 4j core and streaming -->
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-stream</artifactId>
<version>3.0.3</version>
</dependency>
<!-- validator for email-->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.4.0</version>
</dependency>
<!-- java ee api -->
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>3.0.2.Final</version>
<type>pom</type>
<scope>provided</scope>
</dependency>
<!-- Hibernate Dependencies -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.6.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.1.6.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
<scope>test</scope>
</dependency>
<!--mocking deps-->
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<!--Logging-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<scope>test</scope>
</dependency>
<!-- hsqldb -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.2.9</version>
<scope>test</scope>
</dependency>
</dependencies>
Test
#RunWith(PowerMockRunner.class)
#PrepareForTest(DaoLoader.class)
#PowerMockIgnore("javax.persistence.*")
public class UserParserTest {
private static EntityManagerFactory emf;
private UserParser parser;
private UserDao dao;
private EntityManager em;
#BeforeClass
public static void initializeEMF(){
emf = Persistence.createEntityManagerFactory("testing");
}
#AfterClass
public static void closeEntityManagerFactory() {
emf.close();
}
#Before
public void setUp() throws Exception {
em = emf.createEntityManager();
em.getTransaction().begin();
dao = new UserDao(em);
PowerMock.mockStatic(DaoLoader.class);
EasyMock.expect(DaoLoader.loadDao("java:module/UserDao")).andReturn(dao);
PowerMock.replay(DaoLoader.class);
parser = new UserParser();
}
#After
public void rollbackTransaction() {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
if (em.isOpen()) {
em.close();
}
PowerMock.verify(DaoLoader.class);
}
#Test
public void testParse() throws Exception {
parser.parse("test_username");
}
exception
javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of mypackage.beans.User.id
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1306)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:871)
at mypackage.dao.UserDao.getOrCreate(UserDao.java:39)
at mypackage.filters.UserParser.parse(UserParser.java:26)
at mypackage.filters.UserParserTest.testParse(UserParserTest.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:101)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:77)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:195)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of mypackage.beans.User.id
at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:62)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:341)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4425)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4147)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:209)
at org.hibernate.event.internal.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:495)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:118)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:78)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:844)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:819)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:823)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:865)
... 35 more
Caused by: java.lang.IllegalArgumentException: Can not set long field mypackage.beans.User.id to mypackage.beans.User
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:55)
at sun.reflect.UnsafeLongFieldAccessorImpl.getLong(UnsafeLongFieldAccessorImpl.java:60)
at sun.reflect.UnsafeLongFieldAccessorImpl.get(UnsafeLongFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:372)
at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:59)
... 46 more

After further testing today I discovered that the problem is being caused by Powermock after testing the Entity class directly without the dao and the mocking my tests pass. Once I add the mock back in the tests fail.
I fixed this by modifiying the #PowerMockIgnore annotation and adding the package where all of my JPA entites were. This test now passes.
#RunWith(PowerMockRunner.class)
#PrepareForTest(DaoLoader.class)
#PowerMockIgnore({"javax.persistence.*","mypackage.beans.*"})
public class UserParserTest {
private static EntityManagerFactory emf;
private UserParser parser;
private UserDao dao;
private EntityManager em;
#BeforeClass
public static void initializeEMF(){
emf = Persistence.createEntityManagerFactory("testing");
}
#AfterClass
public static void closeEntityManagerFactory() {
emf.close();
}
#Before
public void setUp() throws Exception {
em = emf.createEntityManager();
em.getTransaction().begin();
dao = new UserDao(em);
PowerMock.mockStatic(DaoLoader.class);
EasyMock.expect(DaoLoader.loadDao("java:module/UserDao")).andReturn(dao);
PowerMock.replay(DaoLoader.class);
parser = new UserParser();
}
#After
public void rollbackTransaction() {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
if (em.isOpen()) {
em.close();
}
PowerMock.verify(DaoLoader.class);
}
#Test
public void testParse() throws Exception {
parser.parse("test_username");
}

Related

Java Spring - 415 Unsupported Media Type

Here is my Controller:
#RestController
public class UserController {
#RequestMapping(value = "/test", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public User someName(#RequestBody User user){
System.out.println(user.toString());
return user;
}
}
User class:
#Entity
#Table(name = "user")
public class User {
#Id #GeneratedValue
#Column(name = "id")
private Integer id;
private String name;
private String secondname;
private String email;
public User() {
}
public User(Integer id, String name, String secondname, String email) {
this.id = id;
this.name = name;
this.secondname = secondname;
this.email = email;
}
public User(String name, String secondname, String email) {
this.name = name;
this.secondname = secondname;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "secondname")
public String getSecondname() {
return secondname;
}
public void setSecondname(String secondname) {
this.secondname = secondname;
}
#Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return new StringBuilder().append(this.name).append(", ").append(this.secondname).append(", ")
.append(this.email).toString();
}
}
And my 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>pl</groupId>
<artifactId>javalab</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>javalab Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<java-version>1.7</java-version>
</properties>
<repositories>
<!-- Repository for ORACLE JDBC Driver -->
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Servlet API -->
<!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Jstl for jsp page -->
<!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- JSP API -->
<!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- Spring dependencies -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- Hibernate -->
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.8.Final</version>
</dependency>
<!-- MySQL JDBC driver -->
<!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- Oracle JDBC driver -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- SQLServer JDBC driver (JTDS) -->
<!-- http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Mail Start -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
<!-- Mail End -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.8.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
</dependencies>
<build>
<finalName>javalab</finalName>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>
When I want to post in in postman:
{
"name": "test",
"secondname": "test",
"email": "test#test.pl"
}
I have an error: 415 Unsupported Media type
More precisely I have: The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
In postman I choose raw and JSON (application/json). As headers I have written: Content-Type as key and application/json as value.
Somebody have any idea what I'm doing wrong?
You can use the chrome's inspect to see the HTTP header of your postman's request.Check whether the content-Type is corrent.
This is so common in spring. Make your entity serializable.

Spring and hibernate integration Could not open JPA

I am currently developing a java/jee app using spring as framework and hibernate as orm.I am using the generic dao design pattern.I want to add a courrier Object to the db but i don't know why i got this error.
this is my log
Exception in thread "main" org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NoSuchMethodError: org.hibernate.Session.getFlushMode()Lorg/hibernate/FlushMode;
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:431)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:447)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:277)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
at biz.picosoft.daoImpl.CourrierDaoImpl$$EnhancerBySpringCGLIB$$61c46376.insert(<generated>)
at biz.picosoft.mains.TestHibernate.main(TestHibernate.java:26)
Caused by: java.lang.NoSuchMethodError: org.hibernate.Session.getFlushMode()Lorg/hibernate/FlushMode;
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.prepareFlushMode(HibernateJpaDialect.java:176)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:162)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
... 8 more
this is my context
<?xml version="1.0" encoding="UTF-8"?>
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="biz.picosoft.entity" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true"></property>
<property name="showSql" value="true"></property>
</bean>
</property>
</bean>
<context:component-scan base-package="biz.picosoft" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mailmanager" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="defaultAutoCommit" value="true" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="contactDaoImpl" class="biz.picosoft.daoImpl.ContacteDaoImpl" />
<bean id="SociétéDaoImpl" class="biz.picosoft.daoImpl.SociétéDaoImpl" />
<bean id="sociétéDaoImpl" class="biz.picosoft.daoImpl.SociétéDaoImpl" />
<bean id="courrierDaoImpl" class="biz.picosoft.daoImpl.CourrierDaoImpl"></bean>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:annotation-driven proxy-target-class="true" />
</beans>
this is my pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>BackEndFinalVersion</groupId>
<artifactId>BackEndFinalVersion</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.alfresco.cmis.client/alfresco-opencmis-extension -->
<dependency>
<groupId>org.alfresco.cmis.client</groupId>
<artifactId>alfresco-opencmis-extension</artifactId>
<version>0.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-ldap</artifactId>
<version>5.17.0</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.168</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-spring</artifactId>
<version>5.22.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-engine</artifactId>
<version>5.22.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.168</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-spring</artifactId>
<version>5.22.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
</project>
this is my generic daoImpl
package biz.picosoft.daoImpl;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import biz.picosoft.dao.GenericDao;
#Transactional(readOnly = false)
public class GenericDaoImp<T> implements GenericDao<T> {
#PersistenceContext
private EntityManager em;
protected Class<T> daoType;
public GenericDaoImp() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
daoType = (Class) pt.getActualTypeArguments()[0];
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public Class<T> getDaoType() {
return daoType;
}
public void setDaoType(Class<T> daoType) {
this.daoType = daoType;
}
public void insert(T t) {
// TODO Auto-generated method stub
em.persist(t);
}
public void update(T t) {
// TODO Auto-generated method stub
em.merge(t);
}
public void delete(T t) {
// TODO Auto-generated method stub
Object managed = em.merge(t);
em.remove(managed);
}
public T findById(Class<T> t, String id) {
// TODO Auto-generated method stub
return em.find(daoType, id);
}
public List<T> findAll() {
// TODO Auto-generated method stub
Query query = em.createQuery("SELECT e FROM " + daoType.getName() + " e");
return (List<T>) query.getResultList();
}
}
my entity
package biz.picosoft.entity;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class Société implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idSociété")
int idSociété;
#Column(name = "nom")
String nom;
#Column(name = "email")
String email;
#Column(name = "télèphone")
String télèphone;
#Column(name = "adress")
String adress;
#OneToMany
private Collection<Contacte> contacts;
public Société(String nom, String email, String télèphone, String adress) {
super();
this.nom = nom;
this.email = email;
this.télèphone = télèphone;
this.adress = adress;
}
public Société() {
super();
}
public int getIdSociété() {
return idSociété;
}
public void setIdSociété(int idSociété) {
this.idSociété = idSociété;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTélèphone() {
return télèphone;
}
public void setTélèphone(String télèphone) {
this.télèphone = télèphone;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public Collection<Contacte> getContacts() {
return contacts;
}
public void setContacts(Collection<Contacte> contacts) {
this.contacts = contacts;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + idSociété;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Société other = (Société) obj;
if (idSociété != other.idSociété)
return false;
return true;
}
}
my main
package biz.picosoft.mains;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import biz.picosoft.dao.ContacteDao;
import biz.picosoft.daoImpl.ContacteDaoImpl;
import biz.picosoft.daoImpl.SociétéDaoImpl;
import biz.picosoft.entity.Contacte;
import biz.picosoft.entity.Société;
public class TestDaoS {
public static void main(String[] args) {
// TODO Auto-generated method stub
Société société=new Société("pico", "pico#gmail.com", "74255546", "el ghazella");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
SociétéDaoImpl sociétéDao=(SociétéDaoImpl) context.getBean("sociétéDaoImpl");
//ContacteDaoImpl contacteDaoImpl = (ContacteDaoImpl) context.getBean("contactDaoImpl");
sociétéDao.insert(société);
Contacte contacte=new Contacte("imed", "imed#pico.biz", "7424554", "ghazella", société);
Contacte contacte2=new Contacte("med", "med#pico.biz", "7424554", "ghazella", société);
//contacteDaoImpl.insert(contacte);
//contacteDaoImpl.insert(contacte2);
System.out.println("list contacts"+sociétéDao.findAll().get(0).getContacts());
}
}
It's a common issue with Spring 4.2 and Hibernate 5.2 integration, because Spring 4.2 version supports only Hibernate versions up to 5.1.
There's even a Bug reported for this issue in the Spring community, you can check it :
Support for Hibernate ORM 5.2, which is claiming that:
Hibernate ORM 5.2 got released just in time for Spring Framework 4.3. Let's do everything we can to support it right away, in particular upgrading our spring-orm-hibernate5 build to 5.2 while retaining compatbility with 5.0 and 5.1.
For further details you can check the following posts too:
Integrate Hibernate 5.2 with Spring framework 4.x
HibernateTemplate is throwing java.lang.NoSuchMethodError: org.hibernate.Session.getFlushMode() -- Spring4.2.6, Hibernate5.2

org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns: [org.hibernate.mapping.Column(lisOfAddresses)]

I am making a hibernate small application in which i am getting the following exception
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.Collection, for columns: [org.hibernate.mapping.Column(lisOfAddresses)]
I have read several posts but unable to find the solution.
can anyone tell me why the exception is coming. The code is as below:
UserDetails.java
package com.sdnext.hibernate.tutorial.dto;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Table;
import org.hibernate.annotations.CollectionId;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
#Entity
#Table (name="USER_DETAIL")
public class UserDetails
{
#Id
#Column(name="USER_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int userId;
#Column(name="USER_NAME")
private String userName;
#ElementCollection
#JoinTable(name="USER_ADDRESS",
joinColumns=#JoinColumn(name="USER_ID"))
#GenericGenerator(strategy="hilo", name = "hilo-gen")
#CollectionId(columns = { #Column(name="ADDRESS_ID") }, generator = "hilo-gen", type = #Type(type="long"))
private Collection<Address> lisOfAddresses = new ArrayList<Address>();
public Collection<Address> getLisOfAddresses() {
return lisOfAddresses;
}
public void setLisOfAddresses(Collection<Address> lisOfAddresses) {
this.lisOfAddresses = lisOfAddresses;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString()
{
return "[User Name: "+userName+"\n Office Address: "+lisOfAddresses+"]";
}
}
HibernateTestDemo.java
package com.sdnext.hibernate.tutorial;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.sdnext.hibernate.tutorial.dto.Address;
import com.sdnext.hibernate.tutorial.dto.UserDetails;
public class HibernateTestDemo {
public static void main(String[] args)
{
UserDetails user = new UserDetails();
//user.setUserId(1);
user.setUserName("Dinesh Rajput");
Address address1 = new Address();
address1.setStreet("First Street");
address1.setCity("First City");
address1.setState("First State");
address1.setPincode("First Pin");
Address address2 = new Address();
address2.setStreet("Second Street");
address2.setCity("Second City");
address2.setState("Second State");
address2.setPincode("Second Pin");
user.getLisOfAddresses().add(address1);
user.getLisOfAddresses().add(address2);
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
Address.java
package com.sdnext.hibernate.tutorial.dto;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable //for value object it is not is entity object. Value object means does not have real meaning for self individually.
public class Address
{
#Column(name="STREET_NAME")
private String street;
#Column(name="CITY_NAME")
private String city;
#Column(name="STATE_NAME")
private String state;
#Column(name="PIN_CODE")
private String pincode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String toString()
{
return " {Street: "+street+" City: "+city+" State: "+state+" Pincode: "+pincode+" }";
}
}
Hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernateDB</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Show all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.sdnext.hibernate.tutorial.dto.UserDetails"/>
</session-factory>
</hibernate-configuration>
As per your entity structure you have
UserDetails which can have multiple Address
but Address entity doesn't have any link to UserDetails
Pls change
#ElementCollection
#JoinTable(name="USER_ADDRESS", joinColumns=#JoinColumn(name="USER_ID"))
#GenericGenerator(strategy="hilo", name = "hilo-gen")
#CollectionId(columns = { #Column(name="ADDRESS_ID") }, generator = "hilo-gen", type = #Type(type="long"))
private Collection<Address> lisOfAddresses = new ArrayList<Address>();
to
#OneToMany(mappedBy="userDetails")
Collection<Address> colAddress;
and in Address entity add
#ManyToOne
#JoinColumn(name="USER_DETAIL_ID")
public UserDetails userDetails;
In comment it says too long, so iam posting it here, the following is my pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.technicalkeeda</groupId>
<artifactId>HibernateExamples</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Spring and Hibernate Examples</name>
<properties>
<spring.version>4.3.7.RELEASE</spring.version>
<spring.security.version>4.2.1.RELEASE</spring.security.version>
<hibernate.version>4.3.9.Final</hibernate.version>
<servlet.api.version>3.1.0</servlet.api.version>
<jsp.api.version>2.2</jsp.api.version>
<jstl.version>1.2</jstl.version>
<jdk.version>1.8</jdk.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>mysql</groupId> -->
<!-- <artifactId>mysql-connector-java</artifactId> -->
<!-- <version>5.1.9</version> -->
<!-- </dependency> -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<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>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.3</version>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.slf4j</groupId> -->
<!-- <artifactId>slf4j-api</artifactId> -->
<!-- <version>1.7.25</version> -->
<!-- </dependency> -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- JavaConfig need this library -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<!-- Spring AOP + AspectJ -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
</dependencies>
</project>

Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/io/STAXEventReader

I'm using JPA + Hibernate 5. And I have a problem with dom4j.
Thank you very much.
Class Empleado.java-->
#Entity
#Table(name = "EMPLEADO")
public class Empleado implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "COD_EMPLEADO")
private Long codigo;
#Column(name = "APELLIDOS")
private String apellidos;
#Column(name = "NOMBRE")
private String nombre;
#Column(name = "FECHA_NACIMIENTO")
private Date fechaNacimiento;
public Empleado() {
}
public Empleado(Long codigo, String apellidos, String nombre, Date fechaNacimiento) {
this.codigo = codigo;
this.apellidos = apellidos;
this.nombre = nombre;
this.fechaNacimiento = fechaNacimiento;
}
public Long getCodigo() {
return codigo;
}
public void setCodigo(Long codigo) {
this.codigo = codigo;
}
public String getApellidos() {
return apellidos;
}
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Date getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(Date fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
#Override
public String toString() {
return "Empleado [codigo=" + codigo + ", apellidos=" + apellidos + ", nombre=" + nombre + ", fechaNacimiento="
+ fechaNacimiento + "]";
}
}
Class TestEmpleado:-->
public class TestEmpleados {
private static EntityManager manager;
private static EntityManagerFactory emf;
#SuppressWarnings("unchecked")
public static void main(String[] args) {
emf = Persistence.createEntityManagerFactory("Persistencia");
manager = emf.createEntityManager();
List<Empleado> empleados = (List<Empleado>) manager.createQuery("FROM Empleado").getResultList();
System.out.println(empleados.size() + "Empleados");
}
}
This is my persistence.xml:-->
<?xml version="1.0" encoding="UTF-8" ?>
<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"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="Persistencia">
<class>es.makigas.hibernate.modelo.Empleado</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem/test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
</persistence>
And at last this is my POM:-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>es.makigas</groupId>
<artifactId>hibernate-jpa-ejemplo</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.191</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
When I execute the TestEmpleados I get the following error-->
mar 17, 2017 11:18:07 AM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: Persistencia
...]
mar 17, 2017 11:18:07 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
mar 17, 2017 11:18:07 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
mar 17, 2017 11:18:07 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/io/STAXEventReader
at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:87)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:180)
at org.hibernate.jpa.boot.spi.Bootstrap.getEntityManagerFactoryBuilder(Bootstrap.java:34)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilder(HibernatePersistenceProvider.java:165)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:114)
at org.hibernate.jpa.HibernatePersistenceProvider.getEntityManagerFactoryBuilderOrNull(HibernatePersistenceProvider.java:71)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:52)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at es.makigas.hibernate.tests.TestEmpleados.main(TestEmpleados.java:19)
Caused by: java.lang.ClassNotFoundException: org.dom4j.io.STAXEventReader
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 11 more
What I see in pom.xml that two dependencies are mismatching - Hibernate 5.1.0 and JPA 1.0.2
If you want to make use of Hibernate 5.1.0 then you should use JPA 2.1. Please make this change and it should work fine.
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.0</version>
</dependency>
Hibernate core 5.1.0.Final include dom4j-1.6.1 jar which throws this error. To fix this, need to exclude dom4j-1.6.1 from hibernate-core and include dom4j-1.6 in your pom.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.0.Final</version>
<exclusions>
<exclusion>
<artifactId>jta</artifactId>
<groupId>javax.transaction</groupId>
</exclusion>
<!-- Exclude SLF4j to avoid version conflicts (we have 1.6.6, this drags
in 1.6.1) -->
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<!-- Exclude dom4j to avoid version conflicts (we have 1.6, this drags
in 1.6.1) -->
<exclusion>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- add dom4j in the correct version -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6</version>
</dependency>

javax.persistence.OneToMany.orphanRemoval<>Z

I've searched everywhere but I didn't found a good answer.
I am developping a maven application using Hibernate + Spring + Mysql.
Here is my application-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http:...">
<bean id='dataSource' class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/university"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</bean>
<bean id='sessionFactory' class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.university.entities.Course</value>
<value>com.university.entities.Student</value>
<value>com.university.entities.Teacher</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
</props>
</property>
</bean>
<bean id='transactionManager' class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref='sessionFactory'/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config/>
<context:component-scan base-package="com.university.dao"></context:component-scan>
</beans>
and Here is my pom.xml :
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.2.4.RELEASE</spring.version>
<hibernate.version>3.6.7.Final</hibernate.version>
<jsf.version>2.2.4</jsf.version>
<slf4j.version>1.7.1</slf4j.version>
<primefaces.version>4.0</primefaces.version>
</properties>
<dependencies>
<!-- Tests unitaires avec junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- antlr -->
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr</artifactId>
<version>3.5.1</version>
</dependency>
<!-- Package entities -->
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0-rev-1</version>
<scope>provided</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
<scope>runtime</scope>
</dependency>
<!-- JSF dependencies -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>${jsf.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Primefaces dependency -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>${primefaces.version}</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
<!-- javassist -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.16</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
But when I try to test a simple DAO as :
package com.university.dao.test;
import java.util.List;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.university.dao.StudentDAO;
import com.university.entities.Student;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:application-context.xml" })
public class StudentDAOTest extends TestCase {
private static Log LOG = LogFactory.getLog(StudentDAOTest.class);
#Autowired
private StudentDAO studentDAO;
#Test
public void testFindAll() {
List<Student> listStudent = studentDAO.findAll();
LOG.debug(listStudent);
assertNotNull(listStudent);
}
#Test
public void testCreateOrUpdate() {
Student newStudent = new Student("Abderrahmen ISSA", "07701607");
studentDAO.createOrUpdate(newStudent);
assertNotNull(newStudent.getId());
}
#Test
public void testFindById() {
Integer id = 2;
Student student = studentDAO.findById(id);
assertNotNull(student);
}
#Test
public void testRemove() {
Student userToRemove = new Student("User To Test Remove", "11111111");
studentDAO.createOrUpdate(userToRemove);
Integer id = userToRemove.getId();
studentDAO.remove(userToRemove);
Student student = studentDAO.findById(id);
assertNull(student);
}
}
The Student class is :
package com.university.entities;
// Generated 20 oct. 2013 20:53:03 by Hibernate Tools 3.4.0.CR1
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Student generated by hbm2java
*/
#Entity
#Table(name = "student", catalog = "university")
public class Student implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String mail;
private Date birthDate;
private String birthPlace;
private String cin;
private Integer mobile;
private Set<Course> courses = new HashSet<Course>(0);
public Student() {
}
public Student(String mail, String cin) {
this.mail = mail;
this.cin = cin;
}
public Student(String name, String mail, Date birthDate, String birthPlace,
String cin, Integer mobile, Set<Course> courses) {
this.name = name;
this.mail = mail;
this.birthDate = birthDate;
this.birthPlace = birthPlace;
this.cin = cin;
this.mobile = mobile;
this.courses = courses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "name", length = 45)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "mail", nullable = false, length = 45)
public String getMail() {
return this.mail;
}
public void setMail(String mail) {
this.mail = mail;
}
#Temporal(TemporalType.DATE)
#Column(name = "birthDate", length = 10)
public Date getBirthDate() {
return this.birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Column(name = "birthPlace", length = 45)
public String getBirthPlace() {
return this.birthPlace;
}
public void setBirthPlace(String birthPlace) {
this.birthPlace = birthPlace;
}
#Column(name = "cin", nullable = false, length = 45)
public String getCin() {
return this.cin;
}
public void setCin(String cin) {
this.cin = cin;
}
#Column(name = "mobile")
public Integer getMobile() {
return this.mobile;
}
public void setMobile(Integer mobile) {
this.mobile = mobile;
}
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(name = "course_has_student", catalog = "university", joinColumns = { #JoinColumn(name = "Student_id", nullable = false, updatable = false) }, inverseJoinColumns = { #JoinColumn(name = "Course_id", nullable = false, updatable = false) })
public Set<Course> getCourses() {
return this.courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
#Override
public String toString() {
return "Student [name=" + name + ", mail=" + mail + ", cin=" + cin
+ "]";
}
}
The StudentDAOImpl :
package com.university.dao.impl;
import org.springframework.stereotype.Repository;
import com.university.dao.StudentDAO;
import com.university.entities.Student;
#Repository("studentDAO")
public class StudentDAOImpl extends GenericDAOImpl<Student> implements
StudentDAO {
}
The GenericDAOImpl :
package com.university.dao.impl;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.university.dao.GenericDAO;
#Transactional
public abstract class GenericDAOImpl<T> implements GenericDAO<T> {
#Autowired
protected SessionFactory sessionFactory;
/**
* Unit.
*/
private final Class<T> entityBeanType;
/**
* Instantiates a new GenericServiceImpl.
*/
#SuppressWarnings("unchecked")
public GenericDAOImpl() {
this.entityBeanType = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected final Session getCurrentSession() {
if (sessionFactory == null) {
throw new IllegalStateException(
"Session Factory has not been set on DAO before usage");
}
return sessionFactory.getCurrentSession();
}
/**
* Gets the entity bean type.
*
* #return the entity bean type
*/
public final Class<T> getEntityBeanType() {
return entityBeanType;
}
public void createOrUpdate(T entity) {
getCurrentSession().saveOrUpdate(entity);
}
#SuppressWarnings("unchecked")
public List<T> findAll() {
return getCurrentSession().createQuery(
"from " + getEntityBeanType().getName()).list();
}
#SuppressWarnings("unchecked")
public T findById(Integer id) {
T entity = (T) getCurrentSession().get(getEntityBeanType(), id);
return entity;
}
public void remove(T entity) {
getCurrentSession().delete(entity);
}
}
I can run the DAOTest on eclipse well but with mvn test I get :
org.springframework.beans.factory.BeanCreationEception : Error
creating bean with name 'sessionFactory' defined in class path
resource [application-context.xml] : Invocation of init method failed;
nested exception is java.lang.NoSuchMethodError :
javax.persistence.OneToMany.orphanRemoval<>Z.
Help please !
You have a library conflict. Have you set this up as Hibernate project in Eclipse so that Eclipse added necessary JARs to the classpath? This would explain why it works in Eclipse but not in the Maven build.
Anyway, ensure the Hibernate library versions match e.g 4.1.8.Final and remove the javax.persistence-api dependency.
This all you should need in your POM regarding Hibernate. Everything else will be resolved transitively by Maven.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>

Categories