javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread cannot reliably process - spring

I am trying to upgrade Spring from 4.0.6 to 4.3.9 version. While doing so I am getting following error "javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread". Entire code was working fine earlier but I am getting this error just because of library upgrade. Hibernate version which is being used in my project is 4.3.7.
Here is my applicationcontext.xml
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jaxws="http://cxf.apache.org/jaxws"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="premier" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#***:1521:PSPRODDB" />
<property name="username" value="**" />
<property name="password" value="*****" />
</bean>
<!-- entity manager configuration -->
<!--<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- externals -->
<bean id="mapperFactory" class="org.dozer.spring.DozerBeanMapperFactoryBean">
<property name="mappingFiles" value="classpath*:dozerBeanMapping.xml" />
</bean>
</beans>
My Entity class
#SuppressWarnings("serial")
#Entity
#Table(name = "ROLES")
#NamedQueries({
#NamedQuery(name = "RoleModuleMO.findById", query = "SELECT rolemodule FROM RoleModuleMO rolemodule WHERE rolemodule.id =:id");
#Proxy(lazy = false)
#EntityListeners(value = SimpleAuditListener.class)
public class RoleModuleMO implements Serializable, SimpleAuditable {
public RoleModuleMO () {
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "ROLEMODULE_ID_SQ")
#SequenceGenerator(name = "ROLEMODULE_ID_SQ", sequenceName = "ROLEMODULE_ID_SQ")
private Long id;
#Column(name="ISVISIBLE", nullable = false)
private Boolean isVisible;
#Column(name="ISENABLED", nullable = false)
private Boolean isEnabled;
#Column(name="NAME", nullable = false)
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getVisible() {
return isVisible;
}
public void setVisible(Boolean visible) {
isVisible = visible;
}
public Boolean getEnabled() {
return isEnabled;
}
public void setEnabled(Boolean enabled) {
isEnabled = enabled;
}
}
My Service class
#Transactional
public class RolesServiceImpl implements RolesService {
#PersistenceContext
private EntityManager em;
private RolesDAO rolesDAO;
private Mapper mapper;
public RolesServiceImpl(RolesDAO rolesDAO, Mapper mapper) {
this.rolesDAO = rolesDAO;
this.mapper = mapper;
}
#Transactional
public RoleModule saveOrUpdateModule(RoleModule vo) {
RoleModuleMO mo = new RoleModuleMO();
mapper.map(vo, mo);
mo = rolesDAO.saveOrUpdateModule(mo);
vo = mapper.map(mo, RoleModule.class);
return vo;
}
}
This was working in spring 4.0.6 and after upgrading to 4.3.9 facing the error.
Is there any changes made by spring community which is causing this error or there is something else which I need to change?
Thanks in advance.

Related

my code is executed successfully but data not stored in database with spring and hibernate

when i am going to execute this program.
my program is successfully executed but it doesn't store data in database.
what is the problem in this program.
this is my Employee.java class
package com.spring.demo;
public class Employee {
private int id;
private String name;
private float salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
this is my EmployeeDao.java class
package com.spring.demo;
import org.springframework.orm.hibernate5.HibernateTemplate;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void saveEmployee(Employee e) {
Integer i = (Integer) template.save(e);
if (i > 0) {
System.out.println("Success");
} else {
System.out.println("Not Success");
}
}
public void updateEmployee(Employee e) {
template.update(e);
}
public void deleteEmployee(Employee e) {
template.delete(e);
}
}
this is my Test.java class
package com.spring.demo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext bean = new
ClassPathXmlApplicationContext("spring.xml");
EmployeeDao emp = (EmployeeDao) bean.getBean("obj");
Employee e = new Employee();
e.setId(2);
e.setName("Amit Goyal");
e.setSalary(40000);
emp.saveEmployee(e);
// emp.updateEmployee(e);
bean.close();
}
}
this is my Employee.hbm.xml file
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.spring.demo.Employee" table="amit1234">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
and last this is my spring.xml file
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
4.2.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="tiger" />
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template"
class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
<property name="checkWriteOperations" value="false"></property>
</bean>
<bean id="obj" class="com.spring.demo.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>
In this configuration you are missing transaction management configuration. Use #transactional annotation over your service method.
In you situation data is not committing in the database it just save the data and not commit the data in database.

spring querydsl I don't want start a transaction

Entity:
package com.test.entity
#Entity
#Table(name="TEST_TABLE")
public class TestTable implements HasMapping, PrimaryKey<Long>, Serializable {
public static final String TABLE_NAME = "TEST_TABLE";
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID", nullable=false)
private Long id;
#Id
#Column(name="Name", nullable=false)
private String name;
#Temporal(value=TemporalType.TIMESTAMP)
#Column(name="CREATE_TIME", nullable=true)
#CreatedDate
private Date createTime;
#Column(name="CREATE_USER", nullable=true, length=32)
#CreatedBy
private String createUser;
#Temporal(value=TemporalType.TIMESTAMP)
#Column(name="LST_UPD_TIME", nullable=true)
#LastModifiedDate
private Date lstUpdTime;
#Column(name="LST_UPD_USER", nullable=true, length=32)
#LastModifiedBy
private String lstUpdUser;
#Column(name="JPA_VERSION", nullable=false)
#Version
private Integer jpaVersion;
......
}
QPath
package com.test.qpath
#Generated("com.mysema.query.codegen.EntitySerializer")
public class QTestTable extends EntityPathBase<TestTable> {
private static final long serialVersionUID = -1751805455;
public static final QTestTable testTable = new QTestTable("testTable");
public final NumberPath<Long> id = createNumber("id", Long.class);
public final DateTimePath<java.util.Date> createTime = createDateTime("createTime", java.util.Date.class);
public final StringPath createUser = createString("createUser");
public final NumberPath<Integer> jpaVersion = createNumber("jpaVersion", Integer.class);
public final DateTimePath<java.util.Date> lstUpdTime = createDateTime("lstUpdTime", java.util.Date.class);
public final StringPath lstUpdUser = createString("lstUpdUser");
public QTestTable(String variable) {
super(TestTable.class, forVariable(variable));
}
#SuppressWarnings("all")
public QTestTable(Path<? extends TestTable> path) {
super((Class)path.getType(), path.getMetadata());
}
public QTestTable(PathMetadata<?> metadata) {
super(TestTable.class, metadata);
}
......
}
Repository
package com.test.repos
public interface RTestTable extends JpaRepository<TestTable, Long>, QueryDslPredicateExecutor<TestTable> {
}
Service
package com.test.service
#Service
public class TestServiceR() {
#Autowired
private RTestTable rTestTable;
public void handler() {
long id = 1;
TestTable t = rTestTable.findone(id);
}
}
package com.test.service
#Service
public class TestServiceQuery() {
#Autowired
private RTestTable rTestTable;
#PersistenceContext
private EntityManager em;
private QTestTable qTestTable = QTestTable.testTable;
public void handler() {
long id = 1;
JPAQuery query = new JPAQuery(em);
TestTable t = query.from(qTestTable).where(qTestTable.id.eq(id)).singleResult(qTestTable);
}
}
spring config
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="#{env.jdbcUrl}" />
<property name="username" value="#{env.jdbcUsername}" />
<property name="password" value="#{env.jdbcPassword}" />
<property name="initialSize" value="1" />
<property name="minIdle" value="#{env['jdbcMinIdle'] ?: 2 }" />
<property name="maxActive" value="#{env['jdbcMaxActive'] ?: 20}" />
<property name="minEvictableIdleTimeMillis" value="#{env['jdbcMinEvictableIdleTimeMillis'] ?: 1800000}" />
<property name="validationQuery" value="#{env['jdbcTestSql']}" />
<property name="testWhileIdle" value="#{env['jdbcTestWhileIdle']?: false}" />
<property name="testOnBorrow" value="#{env['jdbcTestOnBorrow']?: true}" />
<property name="testOnReturn" value="#{env['jdbcTestOnReturn']?: false}" />
<property name="poolPreparedStatements" value="false" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="-1" />
<property name="filters" value="mergeStat,slf4j" />
<property name="connectionProperties" value="druid.stat.slowSqlMillis=1500;druid.stat.logSlowSql=true" />
<property name="timeBetweenLogStatsMillis" value="900000" />
</bean>
<bean id="emf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="default" />
<property name="packagesToScan">
<list>
<value>com.sunline.ccs.infrastructure.shared.model</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="#{env['jpaDatabaseType']?:'DEFAULT'}" />
<property name="showSql" value="#{env['jpaShowSql']?:false}" />
</bean>
</property>
</bean>
<bean id="sessionFactory" factory-bean="emf" factory-method="getSessionFactory" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
<jpa:repositories base-package="com.test.repos" />
I test TestServiceR.handler() and TestServiceQuery.handler().
I think they don't start a transaction.
but class TestServiceR are start a transaction.
why? how can i set TestServiceR.handler() don't start a transaction.
TestServiceR calls RTestTable.findOne which extends JpaRepository, which is implemented by SimpleJpaRepository, which is annotated with #Transactional(readOnly = true). So, the transaction is started by SimpleJpaRepository.
Is there a particular reason why you are worried about the transaction, given that it does not affect the application adversely (at least not much)? See the comment history for this Spring Data JPA JIRA issue if you are not convinced.
If you still want to override the default behaviour, you can initialise JPA repositories as #EnableJpaRepositories(enableDefaultTransactions = false) (Java configuration) or <jpa:repositories enable-default-transactions="false" ... /> (XML configuration) to prevent the default implementation from creating transactions by default. See this Spring Data JPA JIRA issue for more details.

More than one table found in namespace (, ) - with Spring, Hibernate and JPA

I’m using Spring 4 & Hibernate 5 with JPA and and Oracle Database, i have checked all my code and there is only one entity and a single table with the name LANGUE, My project still refuses to compile because of this error, Can someone help me please ….,
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:faces="http://www.springframework.org/schema/faces"
xmlns:int-security="http://www.springframework.org/schema/integration/security"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/integration/security http://www.springframework.org/schema/integration/security/spring-integration-security-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.collecteJ.crud" />
<context:component-scan base-package="com.collecteJ.crud.entities" />
<context:component-scan base-package="com.collecteJ.crud.test.entities" />
<context:component-scan base-package="com.collecteJ.crud.dao"/>
<context:component-scan base-package="com.collecteJ.crud.test.dao" />
<context:component-scan base-package="com.collecteJ.crud.service"/>
<context:component-scan base-package="com.collecteJ.crud.test.service"/>
<context:component-scan base-package="com.collecteJ.crud.test"/>
<context:component-scan base-package="com.collecteJ.business.compte"/>
<context:component-scan base-package="com.collecteJ.business.compte.impl" />
<context:component-scan base-package="com.collecteJ.business.service"/>
<context:component-scan base-package="com.collecteJ.business.service.impl" />
<context:component-scan base-package="com.collecteJ.business.test" />
<aop:config proxy-target-class="true"/>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value> database.properties</value>
</property>
</bean>
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" >
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="acquireIncrement" value="1"/>
<property name="maxPoolSize" value="10" />
<property name="maxStatements" value="0" />
<property name="minPoolSize" value="5" />
</bean>
<bean id="JDBCDataSource" 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}"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
<property name="generateDdl" value="true" />
<property name="showSql" value="true"/>
</bean>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="dataSource" ref="pooledDataSource" />
<property name="persistenceUnitName" value="collecteJCrudSpringPU"/>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
persitence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="collecteJCrudSpringPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.collecteJ.crud.entities.Account</class>
<class>com.collecteJ.crud.entities.Agence</class>
<class>com.collecteJ.crud.entities.Collecte</class>
<class>com.collecteJ.crud.entities.Collecteur</class>
<class>com.collecteJ.crud.entities.CollecteurCompte</class>
<class>com.collecteJ.crud.entities.Compte</class>
<class>com.collecteJ.crud.entities.Comptecollecte</class>
<class>com.collecteJ.crud.entities.Devise</class>
<class>com.collecteJ.crud.entities.EtatCivil</class>
<class>com.collecteJ.crud.entities.Role</class>
<class>com.collecteJ.crud.entities.TypeTransaction</class>
<class>com.collecteJ.crud.entities.Utilisateur</class>
<class>com.collecteJ.crud.test.entities.Testtable</class>
</persistence-unit>
</persistence>
stack trace
run:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/C:/Users/hpcc/Documents/GoldTelecom/NetBeansProjects/collecteJCrud/build/classes/com/collecteJ/crud/config/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: collecteJCrudSpringPU] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.collecteJ.crud.main.MainTest2.main(MainTest2.java:32)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: collecteJCrudSpringPU] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 12 more
Caused by: org.hibernate.tool.schema.extract.spi.SchemaExtractionException: More than one table found in namespace (, ) : LANGUE
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults(InformationExtractorJdbcDatabaseMetaDataImpl.java:381)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTable(InformationExtractorJdbcDatabaseMetaDataImpl.java:279)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.getTableInformation(DatabaseInformationImpl.java:105)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:162)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:133)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:470)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
... 17 more
Java Result: 1
BUILD SUCCESSFUL (total time: 14 seconds)
Language.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.collecteJ.crud.entities;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* #author Cyrille benito
*/
#Entity
#Table(name = "LANGUE")
#NamedQueries({
#NamedQuery(name = "Langue.findAll", query = "SELECT l FROM Langue l"),
#NamedQuery(name = "Langue.findByCodeLangue", query = "SELECT l FROM Langue l WHERE l.codeLangue = :codeLangue"),
#NamedQuery(name = "Langue.findByReference", query = "SELECT l FROM Langue l WHERE l.reference = :reference"),
#NamedQuery(name = "Langue.findByLibelle", query = "SELECT l FROM Langue l WHERE l.libelle = :libelle"),
#NamedQuery(name = "Langue.findByFormatDateCourte", query = "SELECT l FROM Langue l WHERE l.formatDateCourte = :formatDateCourte"),
#NamedQuery(name = "Langue.findByFormatDateLongue", query = "SELECT l FROM Langue l WHERE l.formatDateLongue = :formatDateLongue"),
#NamedQuery(name = "Langue.findByFormatHeure", query = "SELECT l FROM Langue l WHERE l.formatHeure = :formatHeure"),
#NamedQuery(name = "Langue.findByFormatNumerique", query = "SELECT l FROM Langue l WHERE l.formatNumerique = :formatNumerique"),
#NamedQuery(name = "Langue.findByTaillePartieDecimale", query = "SELECT l FROM Langue l WHERE l.taillePartieDecimale = :taillePartieDecimale"),
#NamedQuery(name = "Langue.findBySeparateurMillier", query = "SELECT l FROM Langue l WHERE l.separateurMillier = :separateurMillier"),
#NamedQuery(name = "Langue.findBySeparateurPartieDecimale", query = "SELECT l FROM Langue l WHERE l.separateurPartieDecimale = :separateurPartieDecimale"),
#NamedQuery(name = "Langue.findByUtilisateuridModif", query = "SELECT l FROM Langue l WHERE l.utilisateuridModif = :utilisateuridModif"),
#NamedQuery(name = "Langue.findByUtilisateuridCrea", query = "SELECT l FROM Langue l WHERE l.utilisateuridCrea = :utilisateuridCrea"),
#NamedQuery(name = "Langue.findByDateCreation", query = "SELECT l FROM Langue l WHERE l.dateCreation = :dateCreation"),
#NamedQuery(name = "Langue.findByDateModification", query = "SELECT l FROM Langue l WHERE l.dateModification = :dateModification")})
public class Langue implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "CODE_LANGUE")
private String codeLangue;
#Basic(optional = false)
#Column(name = "REFERENCE")
private String reference;
#Basic(optional = false)
#Column(name = "LIBELLE")
private String libelle;
#Column(name = "FORMAT_DATE_COURTE")
private String formatDateCourte;
#Column(name = "FORMAT_DATE_LONGUE")
private String formatDateLongue;
#Column(name = "FORMAT_HEURE")
private String formatHeure;
#Column(name = "FORMAT_NUMERIQUE")
private String formatNumerique;
#Column(name = "TAILLE_PARTIE_DECIMALE")
private BigInteger taillePartieDecimale;
#Column(name = "SEPARATEUR_MILLIER")
private String separateurMillier;
#Column(name = "SEPARATEUR_PARTIE_DECIMALE")
private String separateurPartieDecimale;
#Column(name = "UTILISATEURID_MODIF")
private BigInteger utilisateuridModif;
#Column(name = "UTILISATEURID_CREA")
private BigInteger utilisateuridCrea;
#Column(name = "DATE_CREATION")
#Temporal(TemporalType.DATE)
private Date dateCreation;
#Column(name = "DATE_MODIFICATION")
#Temporal(TemporalType.DATE)
private Date dateModification;
public Langue() {
}
public Langue(String codeLangue) {
this.codeLangue = codeLangue;
}
public Langue(String codeLangue, String reference, String libelle) {
this.codeLangue = codeLangue;
this.reference = reference;
this.libelle = libelle;
}
public String getCodeLangue() {
return codeLangue;
}
public void setCodeLangue(String codeLangue) {
this.codeLangue = codeLangue;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public String getFormatDateCourte() {
return formatDateCourte;
}
public void setFormatDateCourte(String formatDateCourte) {
this.formatDateCourte = formatDateCourte;
}
public String getFormatDateLongue() {
return formatDateLongue;
}
public void setFormatDateLongue(String formatDateLongue) {
this.formatDateLongue = formatDateLongue;
}
public String getFormatHeure() {
return formatHeure;
}
public void setFormatHeure(String formatHeure) {
this.formatHeure = formatHeure;
}
public String getFormatNumerique() {
return formatNumerique;
}
public void setFormatNumerique(String formatNumerique) {
this.formatNumerique = formatNumerique;
}
public BigInteger getTaillePartieDecimale() {
return taillePartieDecimale;
}
public void setTaillePartieDecimale(BigInteger taillePartieDecimale) {
this.taillePartieDecimale = taillePartieDecimale;
}
public String getSeparateurMillier() {
return separateurMillier;
}
public void setSeparateurMillier(String separateurMillier) {
this.separateurMillier = separateurMillier;
}
public String getSeparateurPartieDecimale() {
return separateurPartieDecimale;
}
public void setSeparateurPartieDecimale(String separateurPartieDecimale) {
this.separateurPartieDecimale = separateurPartieDecimale;
}
public BigInteger getUtilisateuridModif() {
return utilisateuridModif;
}
public void setUtilisateuridModif(BigInteger utilisateuridModif) {
this.utilisateuridModif = utilisateuridModif;
}
public BigInteger getUtilisateuridCrea() {
return utilisateuridCrea;
}
public void setUtilisateuridCrea(BigInteger utilisateuridCrea) {
this.utilisateuridCrea = utilisateuridCrea;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Date getDateModification() {
return dateModification;
}
public void setDateModification(Date dateModification) {
this.dateModification = dateModification;
}
#Override
public int hashCode() {
int hash = 0;
hash += (codeLangue != null ? codeLangue.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Langue)) {
return false;
}
Langue other = (Langue) object;
if ((this.codeLangue == null && other.codeLangue != null) || (this.codeLangue != null && !this.codeLangue.equals(other.codeLangue))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.collecteJ.crud.entities.Langue[ codeLangue=" + codeLangue + " ]";
}
}
Try to change line
<property name="generateDdl" value="true" />
to:
<property name="generateDdl" value="false" />

Caused by: org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

I need to configure spring + JPA (EntityManager) + Hibernate .
If I had to fetch = FetchType.LAZY run server success
If I had to fetch = FetchType.EAGER run server error:
I using tomcat 7
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: fmis2] Unable to build EntityManagerFactory
...
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: fmis2] Unable to build EntityManagerFactory
...
Caused by: org.hibernate.loader.MultipleBagFetchException: can not simultaneously fetch multiple bags
Please help me. Where I was wrong.
Thanks
Config applicationContext.xml
<context:annotation-config />
<context:component-scan base-package="com.evnit.fmis" />
<jpa:repositories base-package="com.evnit.fmis" />
<!-- START -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/jpa-persistence.xml" />
<property name="persistenceUnitName" value="fmis2" />
<property name="dataSource" ref="fmis2dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.SQLServerDialect" />
<property name="database" value="SQL_SERVER" />
</bean>
</property>
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="fmis2dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
jpa-persistence.xml
<persistence-unit name="fmis2" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jar-file>/WEB-INF/lib/accounting-inf-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/masterdata-inf-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/congno-backend-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/congcudungcu-backend-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/taisan-backend-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/vattu-backend-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/muahang-backend-1.0-SNAPSHOT.jar</jar-file>
</persistence-unit>
Java Code entity
package com.evnit.fmis.accounting.entity;
#Entity
#Table(name = "ChungTu", schema = "ketoan")
public class ChungTu implements java.io.Serializable {
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "chungTu")
public List<DinhKhoan> getDinhKhoans() {
return this.dinhKhoans;
}
public void setDinhKhoans(List<DinhKhoan> dinhKhoans) {
this.dinhKhoans = dinhKhoans;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "chungTu")
public List<Uynhiemchi> getUynhiemchis() {
return this.uynhiemchis;
}
public void setUynhiemchis(List<Uynhiemchi> uynhiemchis) {
this.uynhiemchis = uynhiemchis;
}
}
#Entity
#Table(name = "DinhKhoan", schema = "ketoan")
public class DinhKhoan implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private ChungTu chungTu;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "IdChungtu")
public ChungTu getChungTu() {
return this.chungTu;
}
public void setChungTu(ChungTu chungTu) {
this.chungTu = chungTu;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "dinhKhoan")
public List<HoaDonVat> getHoaDonVats() {
return this.hoaDonVats;
}
public void setHoaDonVats(List<HoaDonVat> hoaDonVats) {
this.hoaDonVats = hoaDonVats;
}
}
#Entity
#Table(name = "Uynhiemchi", schema = "ketoan")
public class Uynhiemchi implements java.io.Serializable {
private ChungTu chungTu;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "IdChungtu", nullable = true)
public ChungTu getChungTu() {
return this.chungTu;
}
public void setChungTu(ChungTu chungTu) {
this.chungTu = chungTu;
}
}
#Entity
#Table(name = "HoaDonVAT", schema = "ketoan")
public class HoaDonVat implements java.io.Serializable {
private DinhKhoan dinhKhoan;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "IdDinhKhoan")
public DinhKhoan getDinhKhoan() {
return this.dinhKhoan;
}
public void setDinhKhoan(DinhKhoan dinhKhoan) {
this.dinhKhoan = dinhKhoan;
}
}
Java Code Dao
public abstract class CommonDao {
#PersistenceContext(unitName = "fmis2")
protected EntityManager entityManager;
}
The problem is the Hibernate specification: he doesn't allow more than one list noted with EAGER. There are some options to bypass this problem:
Use LAZY lists. If you need 'to simulate' a eager relation, use yourList.size() to populate before the query;
Use Set instead List in your data structures.
Other explanations:
Hibernate cannot simultaneously fetch multiple bags
Multiple fetches with EAGER type in Hibernate with JPA
Regards.

Spring injected bean is null

I am using Spring Framework / Data / HATEOAS and trying to add Dozer.
I have the following bean in my spring-config.xml:
<?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:data="http://www.springframework.org/schema/data/jpa"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/cp" />
<property name="username" value="cp_user" />
<property name="password" value="+JMJ+pw0m2d" />
</bean>
<context:component-scan base-package="com.mydomain.data.assembler" />
<data:repositories base-package="com.mydomain.repository" />
<mvc:annotation-driven />
<bean id="dozerFactory" class="org.dozer.spring.DozerBeanMapperFactoryBean" scope="singleton">
<property name="mappingFiles" value="classpath*:/*mapping.xml"/>
</bean>
</beans>
And the following assembler:
#Component
public class UserResourceAssembler {
#Inject
private Mapper dozerBeanMapper;
public UserResource toResource(User user) {
UserResource resource = dozerBeanMapper.map(user, UserResource.class);
resource.add(linkTo(methodOn(UserController.class).get(user.getId())).withSelfRel());
return resource;
}
public User toEntity(UserResource resource) {
User user = dozerBeanMapper.map(resource, User.class);
return user;
}
}
So, - I'm very new to beans and injection - but I guess that the factory bean is ?supposed? to inject the Mapper. But the Mapper is definitely null. I know I'm not doing this right, but what am I doing wrong?
Spring injects its beans into spring managed beans. You are using an unmanaged static context. Change UserResourceAssembler into a managed bean as well:
#Component
public class UserResourceAssembler {
#Inject
private Mapper dozerBeanMapper;
public UserResource toResource(User user) {
}
public User toEntity(UserResource resource) {
}
}
See why can't we autowire static fields in spring.
I would have preferred something like the above. But then I read:
Dozer Singleton Startup Bean injetced as Null
That worked. Here was my implementation.
I removed the bean from spring-config, and the context scan.
I added this class:
#Singleton
public class DozerInstantiator {
public static DozerBeanMapper getInstance(){
return MapperHolder.instance;
}
private static class MapperHolder{
static final DozerBeanMapper instance = new DozerBeanMapper();
}
}
And updated my assembler like this:
public class UserResourceAssembler {
private DozerBeanMapper mapper;
public UserResourceAssembler() {
mapper = DozerInstantiator.getInstance();
}
public UserResource toResource(User user) {
UserResource resource = mapper.map(user, UserResource.class);
resource.add(linkTo(methodOn(UserController.class).get(user.getId())).withSelfRel());
return resource;
}
public User toEntity(UserResource resource) {
User user = mapper.map(resource, User.class);
return user;
}
}

Resources