NoClassDefFoundExpetion: javax/persistence/PersistenceContext Spring ORM with Hibernate - java

I'm new to spring. I.m learning spring from javapoint. After learning some basics of spring from javapoint and spring docs, I moved towards learning hibernate with spring, but in very first try (example), I stucked with the expception: NoClassDefFoundExpetion: javax/persistence/PersistenceContext. To resolve this exception, I've googled and looked for similar kind of situations (and their solutions) on this and this, but nothing helps me.
Here is the full stacktrace: of my exception
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.annotation.internalPersistenceAnnotationProcessor': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/persistence/PersistenceContext
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1105)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1050)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
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:202)
at org.springframework.context.support.PostProcessorRegistrationDelegate.registerBeanPostProcessors(PostProcessorRegistrationDelegate.java:207)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:697)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:526)
at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
at test.Test.main(Test.java:15)
Caused by: java.lang.NoClassDefFoundError: javax/persistence/PersistenceContext
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.<clinit>(PersistenceAnnotationBeanPostProcessor.java:172)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1098)
... 12 more
I'm using eclipse-neon IDE, spring-framework 4.3.2 RELEASE, Hibernate-5.2.2 Final and Oracle 10G(database).There is a STUDENT table in my database having 4-5 entries. Also I've written thespring code using simple (console base) java project and NOT using any build tool. Here is my complete code and libraries list which I'm currently using:
Student.java
public class Student {
private Integer rollNo;
private String name;
/**
* #param rollNo
* #param name
*/
public Student(Integer rollNo, String name) {
super();
this.rollNo = rollNo;
this.name = name;
}
//Getter and setter ....
StudentDAO.java
public class StudentDAO {
private HibernateTemplate hibernateTemplate;
public StudentDAO(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate template) {
this.hibernateTemplate = template;
}
public void saveStudent(Student student) {
hibernateTemplate.save(student);
}
public List<Student> readAll() {
return hibernateTemplate.loadAll(Student.class);
}
}
I'm using java annotation based configuration, So my AppConfig.java is:
#Configuration
public class AppConfig {
#Bean
public DriverManagerDataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource("jdbc:oracle:thin:#localhost:1521/xe", "user", "password");
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactoryBean() {
LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
bean.setDataSource(dataSource());
bean.setMappingResources("xml/student.hbm.xml");
Properties prop = new Properties();
prop.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle9Dialect");
prop.setProperty("hibernate.hbm2ddl.auto", "update");
prop.setProperty("hibernate.show_sql", "true");
bean.setHibernateProperties(prop);
return bean;
}
#Bean
public HibernateTemplate hibernateTemplate() {
HibernateTemplate template = new HibernateTemplate((SessionFactory) sessionFactoryBean());
return template;
}
#Bean
public StudentDAO DAO() {
return new StudentDAO(hibernateTemplate());
}
}
Student.hbm.xml 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="bean.Student" table="student">
<rollNo name="rollNo">
<generator class="assigned"></generator>
</rollNo>
<property name="name"></property>
</class>
</hibernate-mapping>
and here is my Main-Method Class
public class Test {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
StudentDAO dao = context.getBean(StudentDAO.class);
List<Student> list = dao.readAll();
for(Student s: list)
System.out.println(s);
}
}
here is the list of liberaries (with jar file) which I've included in my project:
SPRING
HIBERNATE
Commons logging and ORALCE 10G Driver
And some other too
How to solve the above mentioned exception, which library I've to add/remove or what else I can try to resolve the issue.
Regret for long question
Example Reference
This example is based on source code, available at javapoint

I made slightly changes in my example. Instead of AppConfig.java, I used ApplicationContext.xml. Here is code for 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-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"></property>
<property name="username" value="sachin"></property>
<property name="password" value="sachin476"></property>
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>student.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect
</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>
</bean>
<bean id="d" class="bean.dao.StudentDao">
<property name="template" ref="template"></property>
</bean>
</beans>
and added two more jar files:
>commons-dbcp2-2.1.1.jar
>commons-pool2-2.4.2.jar
for BasicDataSource class.
Now It gives me Exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mysessionFactory' defined in class path resource [xml/ApplicationContext.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
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.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:757)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at test.Test.main(Test.java:15)
Caused by: java.lang.NoClassDefFoundError: org/hibernate/SessionFactory
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetPublicMethods(Class.java:2902)
at java.lang.Class.getMethods(Class.java:1615)
at org.springframework.beans.ExtendedBeanInfoFactory.supports(ExtendedBeanInfoFactory.java:54)
at org.springframework.beans.ExtendedBeanInfoFactory.getBeanInfo(ExtendedBeanInfoFactory.java:46)
at org.springframework.beans.CachedIntrospectionResults.<init>(CachedIntrospectionResults.java:270)
at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:189)
at org.springframework.beans.BeanWrapperImpl.getCachedIntrospectionResults(BeanWrapperImpl.java:173)
at org.springframework.beans.BeanWrapperImpl.getLocalPropertyHandler(BeanWrapperImpl.java:226)
at org.springframework.beans.BeanWrapperImpl.getLocalPropertyHandler(BeanWrapperImpl.java:63)
at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyHandler(AbstractNestablePropertyAccessor.java:725)
at org.springframework.beans.AbstractNestablePropertyAccessor.isWritableProperty(AbstractNestablePropertyAccessor.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1483)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1226)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
... 11 more
But I peeped into hibernate-core-5.2.2-Final.jar, that had definition for SessionFectory.class in org.hibernate package i.e there was class entry named org.hibernate.SessionFactory.class. Now I'm wondering why it gives such exceptions
UPDATE
After lots of try and search on google, I found that hibernate 5 doesn't support oracle10g drivers. so I've updated ojdbc14.jar to ojdbc6.jar, and it works for me

As mentioned here Upgrade your hibernate jpa-jar since the jpa supported version for hibernate4.3+ is 2.1.

Related

Unable to open JDBC Connection for DDL execution

I get the following error with my spring beans,
Error creating bean with name 'employeeRepositoryDAOImple':
Unsatisfied dependency expressed through method 'setSessionFactory'
parameter 0; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'sessionFactory' defined in class path
resource [config.xml]: Invocation of init method failed; nested
exception is org.hibernate.exception.JDBCConnectionException: Unable
to open JDBC Connection for DDL execution
Client.java
public class Client {
public static void main(String arg[]) {
AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml");
EmployeeService employeeService = (EmployeeService) ctx.getBean("empoyeService");
Employee employee1 = new Employee(100001, "Alex", "Account");
Employee employee2 = new Employee(100002, "Sam", "HR");
employeeService.insert(employee1);
employeeService.insert(employee2);
System.out.println("Records are successfully added..");
ctx.close();
}
}
Entity.java
#Entity
public class Employee {
#Id
private int empId;
private String empName;
private String department;
public Employee() {
super();
}
public Employee(int empId,String empName,String deptName)
{
super();
this.empId=empId;
this.empName=empName;
this.department=deptName;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
#Override
public String toString()
{
return "Employee Empid="+empId+" empName="+empName+" department="+department;
}
}
EmployeeService.java
#Service("empoyeService")
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
EmployeeRepository emprepo;
#Override
public void insert(Employee employee) {
// TODO Auto-generated method stub
emprepo.insert(employee);
}
#Override
public int delete(int empid) {
// TODO Auto-generated method stub
return emprepo.delete(empid);
}
}
EmployeeRepositoryDAOImple.java
#Repository
public class EmployeeRepositoryDAOImple implements EmployeeRepository{
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void insert(Employee employee) {
// TODO Auto-generated method stub
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(employee);
tx.commit();
session.close();
}}
Config.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Define Service and Repository beans using auto scan feature of Spring -->
<context:component-scan base-package="com.orm.employee.dao,com.orm.employee.Service" />
<!-- Define DataSource bean using DriverManagerDataSource class of Spring -->
<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/myschema"></property>
<property name="username" value="root"></property>
<property name="password" value="xxxx"></property>
</bean>
<!-- Define sessionFactory bean of Spring class -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.orm.employee.dao" />
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>
Exception
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.UnsatisfiedDependencyException: Error creating bean with name 'employeeRepositoryDAOImple': Unsatisfied dependency expressed through method 'setSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:676)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at com.orm.employee.client.Client.main(Client.java:14)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:273)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1237)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:668)
... 15 more
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:48)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:69)
at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcConnection(ImprovedExtractionContextImpl.java:60)
at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcDatabaseMetaData(ImprovedExtractionContextImpl.java:67)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTables(InformationExtractorJdbcDatabaseMetaDataImpl.java:329)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.getTablesInformation(DatabaseInformationImpl.java:120)
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:65)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:207)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:310)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:615)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741)
... 25 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:353)
at com.mysql.jdbc.Util.getInstance(Util.java:336)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:985)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2938)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:855)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3337)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1217)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1930)
at com.mysql.jdbc.Connection.<init>(Connection.java:716)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:353)
at com.mysql.jdbc.Connection.getInstance(Connection.java:295)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:154)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:145)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:43)
... 42 more
Solution:
Upgrading MySql connector jar from 5.1 to 8.0 fixed the problem - my code was not the problem.
I solved this by correcting mysql credentials in the src > main > application.properties file
Check if your mysql credentials are correct and mysql server is running.
In my case didn't have the right autentication permission for root user.
I knew that because logged to database just only tipying that:
sudo mysql
So, once logged into MySQL I typed that:
SELECT user,authentication_string,plugin,host FROM mysql.user;
And saw the value auth_socket in the plugin column of root user.
So, I typed that:
ALTER USER 'root'#'localhost' IDENTIFIED WITH mysql_native_password BY 'PASSWORD';
Then restarted tomcat and problem solved.
Henceforth, have to log into mysql typing:
mysql -u root -pPASSWORD
Hope It helps someone :)
Check you are hibernating configuration
spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_db
spring.datasource.username=root
spring.datasource.password=r00t
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
My problem was in the timezone configuration. I added:
?useSSL=false&useTimezone=true&serverTimezone=UTC
in application.properties. The whole line looked like this:
db.url= jdbc:mysql://localhost:3306/indigo?useSSL=false&useTimezone=true&serverTimezone=UTC
Can you make the following changes to your code.
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
And add below property in addition and remove the #Autowired from sessionFactory
<bean id="employeeDAO" class="yourbasepackage.EmployeeRepositoryDAOImple">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
this is what worked for me
mysql> CREATE USER 'scilla'#'172.17.0.1' IDENTIFIED BY 'password';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'scilla'#'172.17.0.1' WITH GRANT OPTION;
mysql> flush privileges;
mysql> exit
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/scilla
username: scilla
password: password
jpa:
hibernate:
ddl-auto: validate
database: mysql
show-sql: true
database-platform: org.hibernate.dialect.MySQL5Dialect
hibernate.ddl-auto: update
i had the same problem, i recommand you to revise the way you are establishing the connection to the database via reviewing the configuration(application.properties):
## Spring Datasource Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/(package_name)?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=****
spring.datasource.password=****
## JPA Hibernate Properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
Make sure if you did up a image on docker for DB connection. This happens to me when I don't run Docker Desktop.

Trying to send Email from spring server.Error is creating bean with name 'hourlyJob': Injection of autowired dependencies failed; nested exception

Error creating bean with name 'hourlyJob':
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.mail.javamail.JavaMailSender com.email.job.HourlyJob.mailSenderObj; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.mail.javamail.JavaMailSender] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4853)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
HourlyJob.java
In this class I connected with database to fetch a table "order_info" and checking upon shipment date I tried to send email.
#Repository
#Transactional
public class HourlyJob implements Runnable {
static String emailToRecipient, emailSubject, emailMessage;
static final String emailFromRecipient = "abc#gmail.com";
static ModelAndView modelViewObj;
#Autowired
private JavaMailSender mailSenderObj;
#Override
public void run() {
// Do your daily job here.
System.out.println("Job trigged by scheduler");
try
{
// create our mysql database connection
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://127.0.0.1:3306/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// our SQL SELECT query.
// if you only need a few columns, specify them by name instead of using "*"
String query = "SELECT * FROM order_info";
// create the java statement
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
Date shipmentDate=rs.getDate("shipment_date");
Date today = new Date();
long diff=shipmentDate.getTime()-today.getTime();
long days = TimeUnit.MILLISECONDS.toDays(diff);
if(Math.abs(days)==1)
{
System.out.println("SHIPMENT DATE "+shipmentDate+" Day difference is :"+days);
emailSubject = "Order Notification";
emailMessage = "Please see The following order date.";
emailToRecipient = "1205085.msss#ugrad.cse.buet.ac.bd";
// send email
mailSenderObj.send(new MimeMessagePreparator()
{
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper mimeMsgHelperObj = new MimeMessageHelper(mimeMessage, true, "UTF-8");
mimeMsgHelperObj.setTo(emailToRecipient);
mimeMsgHelperObj.setFrom(emailFromRecipient);
mimeMsgHelperObj.setText(emailMessage);
mimeMsgHelperObj.setSubject(emailSubject);
// Determine If There Is An File Upload. If Yes, Attach It To The Client Email
}
});
System.out.println("\nMessage Send Successfully.... Hurrey!\n");
}
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
BackgroundJobManager.java
In this class I implemented ServletContextListener to schedule HourJob.java each minute.
#WebListener
public class BackgroundJobManager implements ServletContextListener
{
// scheduler
private ScheduledExecutorService scheduler;
#Override
public void contextInitialized(ServletContextEvent event) {
scheduler = Executors.newSingleThreadScheduledExecutor();
// here we schedule HourlyJob
scheduler.scheduleAtFixedRate(new HourlyJob(), 0, 1, TimeUnit.MINUTES);
}
#Override
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdownNow();
}
}
spring-servlet.xml
This is the dispatcher servlet. Here I defined mailSender bean.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean -->
<!-- where the front controller search for controllers -->
<bean id="tilesViewResolver"
class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/layout/default.xml</value>
</list>
</property>
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- setting maximum upload size 15 MB -->
<property name="maxUploadSize" value="15728640" />
</bean>
<!-- mail staff -->
<!-- Spring Email Sender Bean Configuration -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<property name="username" value="abc#gmail.com" />
<property name="password" value="********" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.debug">true</prop>
<prop key="mail.transport.protocol">smtp</prop>
<prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop>
<prop key="mail.smtp.socketFactory.port">465</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<!-- mail staff -->
<mvc:default-servlet-handler/>
</beans>
It says you have no bean of type org.springframework.mail.javamail.JavaMailSender which is weird because it looks like you have configured that in your xml as you've mentioned, do you have getters and setters for JavaMailSender mailSenderObj ? setMailSenderObj(JavaMailSender mailSenderObj) you need getters and setters for private fields. I think you don't for protected with the new Spring version. Otherwise ensure that your spring-servlet.xml is indeed creating those beans. Typically you don't mix servlet stuff with spring stuff so not sure what you are up to there. I recommend only using annotations if you can and just using the latest version of Spring. Good luck.

(TypeConverterDelegate.java:529) - Cannot create copy of Collection type [java.util.ArrayList] - injecting original Collection as-is

I have the program:
public static void main(String[] args)
{
ApplicationContext ctx = ServiceLocator.getApplicationContext(); <-- error
.......}
It has the error message below: I want to eliminate this error which seems coming from JAVA with [DEBUG]. But the program can continue to run. I searched in the google but no luck. I also does not know where is the code wrong. Is it possible to solve this?
14 Nov 2017 16:50:48,288 [DEBUG] (TypeConverterDelegate.java:529) - Cannot create copy of Collection type [java.util.ArrayList] - injecting original Collection as-is
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Collection
at org.springframework.beans.TypeConverterDelegate.convertToTypedCollection(TypeConverterDelegate.java:524)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:201)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:104)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:415)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:657)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:984)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:886)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:479)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:289)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:286)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:188)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:558)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:852)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:422)
at org.springframework.context.access.ContextSingletonBeanFactoryLocator.initializeDefinition(ContextSingletonBeanFactoryLocator.java:143)
at org.springframework.beans.factory.access.SingletonBeanFactoryLocator.useBeanFactory(SingletonBeanFactoryLocator.java:384)
at com.xxxx.ServiceLocator.getApplicationContext(ServiceLocator.java:24)
at com.xxxx.main(mcrpt.java:115)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
at com.xxxx.ServiceLocator.getApplicationContext(ServiceLocator.java:24)
package com.xxxx;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
public class ServiceLocator {
private static ApplicationContext applicationContext;
protected ServiceLocator() {
}
public static ApplicationContext getApplicationContext() {
if (applicationContext == null) {
BeanFactoryLocator locator = ContextSingletonBeanFactoryLocator.getInstance("ApplicationContext.xml");
BeanFactoryReference bfr = locator.useBeanFactory("applicationContext");
BeanFactory factory = bfr.getFactory();
applicationContext = (ApplicationContext) factory;
}
return applicationContext;
}
}
ApplicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="applicationContext"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>ApplicationContext-properties.xml</value>
<value>ApplicationContext-log4j.xml</value>
<value>ApplicationContext-datasource.xml</value>
</list>
</constructor-arg>
</bean>
</beans>
Your bean definition is incorrect.
replace:
<bean id="applicationContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg>
<list>
<value>ApplicationContext-properties.xml</value>
<value>ApplicationContext-log4j.xml</value>
<value>ApplicationContext-datasource.xml</value>
</list>
</constructor-arg>
</bean>
with
<bean id="applicationContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">
<constructor-arg value="ApplicationContext-properties.xml" />
<constructor-arg value="ApplicationContext-log4j.xml" />
<constructor-arg value="ApplicationContext-datasource.xml" />
</bean>

hibernate spring doesn t close connections

I try to use spring and hibernate to populate a database (MySQL). But after ~ 25-30k inserts, i got the following error :
févr. 15, 2017 12:14:27 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: 08001
févr. 15, 2017 12:14:27 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
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.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy28.create(Unknown Source)
at main.Main.recupReq(Main.java:353)
at main.Main.manageCategories(Main.java:140)
at main.Main.transformOldModelToNewModel(Main.java:119)
at main.Main.transferXMLtoDB(Main.java:82)
at main.Main.main(Main.java:59)
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:48)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:102)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:129)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:247)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:254)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:203)
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:56)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:189)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
... 12 more
Caused by: java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:526)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:505)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:479)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:489)
at com.mysql.cj.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:1677)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1601)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:633)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:347)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:219)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:196)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:159)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:99)
... 19 more
Caused by: com.mysql.cj.core.exceptions.CJCommunicationsException: The driver was unable to create a connection due to an inability to establish the client portion of a socket.
This is usually caused by a limit on the number of sockets imposed by the operating system. This limit is usually configurable.
For Unix-based platforms, see the manual page for the 'ulimit' command. Kernel or system reconfiguration may also be required.
For Windows-based platforms, see Microsoft Knowledge Base Article 196271 (Q196271).
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:54)
at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:93)
at com.mysql.cj.core.exceptions.ExceptionFactory.createException(ExceptionFactory.java:133)
at com.mysql.cj.core.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:149)
at com.mysql.cj.mysqla.io.MysqlaSocketConnection.connect(MysqlaSocketConnection.java:83)
at com.mysql.cj.mysqla.MysqlaSession.connect(MysqlaSession.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:1619)
... 32 more
Caused by: java.net.BindException: Address already in use: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mysql.cj.core.io.StandardSocketFactory.connect(StandardSocketFactory.java:202)
at com.mysql.cj.mysqla.io.MysqlaSocketConnection.connect(MysqlaSocketConnection.java:57)
... 34 more
févr. 15, 2017 12:14:27 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFOS: Closing org.springframework.context.support.ClassPathXmlApplicationContext#41906a77: startup date [Wed Feb 15 12:12:59 CET 2017]; root of context hierarchy
févr. 15, 2017 12:14:27 PM org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean destroy
INFOS: Closing JPA EntityManagerFactory for persistence unit 'default'
If i understand correctly, connections to database are not closed correctly and the number of sockets used reach a limit. Problem is connections are normally managed by spring and should not stay open.
I dont want to increase this limit, just close and open a connection each time I insert or update something.
I think the key is to change the application context file, but couldn t find how.
Here are the applicationContext :
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.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
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Activation annotations et scan des classes -->
<context:annotation-config />
<context:component-scan base-package="jpa" />
<!-- Specify the Hibernate properties setting file -->
<context:property-placeholder
location="classpath:hibernate.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- Creation EntityManagerFactory à partir de la dataSource -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="jpa" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
<property name="showSql" value="${hibernate.show_sql}" />
<property name="generateDdl" value="true" />
</bean>
</property>
<!-- <property name="jpaProperties"> -->
<!-- <props> -->
<!-- <prop key="hibernate.hbm2ddl.auto">${hibernate.action}"</prop> -->
<!-- </props> -->
<!-- </property> -->
</bean>
<!-- getionnaire transaction entityManagerFactory -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<!-- activation de l'annotation #Transcationnal -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- activation translation d'execption -->
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"></bean>
</beans
and the property file :
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/calib?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&autoReconnect=true&useSSL=false
jdbc.username=root
jdbc.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=false
hibernate.action=create-drop
Edit : I tried to open and close the ClassPathXmlApplicationContext to renew the connection but the same error happens : java.net.BindException: Address already in use: connect
Edit 2 :
Dao :
package jpa.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import jpa.model.NewModelAttr;
#Repository
#Transactional
public class DaoAttrJpa implements DaoAttr{
#PersistenceContext
private EntityManager em;
#Override
public void create(NewModelAttr obj) {
em.persist(obj);
}
#Override
public void delete(NewModelAttr obj) {
em.remove(em.merge(obj));
}
#Override
public NewModelAttr update(NewModelAttr obj) {
return em.merge(obj);
}
#SuppressWarnings("unchecked")
#Override
public List<NewModelAttr> findAll() {
List<NewModelAttr> liste = null;
Query query = em.createNamedQuery("NewModelAttr.findAll", NewModelAttr.class);
liste = query.getResultList();
return liste;
}
#Override
public NewModelAttr findByPrimaryKey(Integer key) {
return em.find(NewModelAttr.class, key);
}
}
Singleton spring :
package jpa.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
import jpa.dao.*;
#Repository
public class AccessDao {
private static ClassPathXmlApplicationContext context;
private static AccessDao instance = null;
#Autowired
private DaoProject daoProject;
#Autowired
private DaoLink daoLink;
#Autowired
private DaoPath daoPath;
#Autowired
private DaoRequirement daoRequirement;
#Autowired
private DaoScenario daoScenario;
#Autowired
private DaoStep daoStep;
#Autowired
private DaoAttr daoAttr;
#Autowired
private DaoCategory daoCategory;
// private AccessDao() {
// context = new ClassPathXmlApplicationContext("applicationContext.xml");
// daoProject = (DaoProject) context.getBean("daoProjectJpa");
// daoLink = (DaoLink) context.getBean("daoLinkJpa");
// daoPath = (DaoPath) context.getBean("daoPathJpa");
// daoRequirement = (DaoRequirement) context.getBean("daoRequirementJpa");
// daoScenario = (DaoScenario) context.getBean("daoScenarioJpa");
// daoStep = (DaoStep) context.getBean("daoStepJpa");
// daoAttr = (DaoAttr) context.getBean("daoAttrJpa");
// daoCategory = (DaoCategory) context.getBean("daoCategoryJpa");
// }
public static AccessDao getInstance() {
if (AccessDao.instance == null) {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccessDao.instance = (AccessDao) context.getBean("accessDao");
}
return AccessDao.instance;
}
public DaoProject getDaoProject() {
return daoProject;
}
public void setDaoProject(DaoProject daoProject) {
this.daoProject = daoProject;
}
public DaoLink getDaoLink() {
return daoLink;
}
public void setDaoLink(DaoLink daoLink) {
this.daoLink = daoLink;
}
public DaoPath getDaoPath() {
return daoPath;
}
public void setDaoPath(DaoPath daoPath) {
this.daoPath = daoPath;
}
public DaoRequirement getDaoRequirement() {
return daoRequirement;
}
public void setDaoRequirement(DaoRequirement daoRequirement) {
this.daoRequirement = daoRequirement;
}
public DaoScenario getDaoScenario() {
return daoScenario;
}
public void setDaoScenario(DaoScenario daoScenario) {
this.daoScenario = daoScenario;
}
public DaoStep getDaoStep() {
return daoStep;
}
public void setDaoStep(DaoStep daoStep) {
this.daoStep = daoStep;
}
public DaoAttr getDaoAttr() {
return daoAttr;
}
public void setDaoAttr(DaoAttr daoAttr) {
this.daoAttr = daoAttr;
}
public DaoCategory getDaoCategory() {
return daoCategory;
}
public void setDaoCategory(DaoCategory daoCategory) {
this.daoCategory = daoCategory;
}
public static void close() {
if (instance != null) {
instance.destroy();
}
}
private void destroy() {
context.close();
instance=null;
}
}
Also open and close many times was just a test. I usually open at the start and close at the end.
Edit 3:
Here is a part of the code where i insert :
private List<NewModelProject> transformOldModelToNewModel(List<ProjectType> projectsFromXML) {
List<NewModelProject> projectsNewModel = new ArrayList<>();
for (ProjectType projectType : projectsFromXML) {
System.out.println("proj:" + projectType.getName());
NewModelProject project = new NewModelProject();
project.setBaseline(projectType.getBaseline());
project.setDescription(projectType.getDescription());
project.setId(Integer.parseInt(projectType.getId()));
project.setName(projectType.getName());
projectsNewModel.add(project);
dao.getDaoProject().create(project);
objectToUpdate.add(project);
manageCategories(projectType, project);
manageScenarios(projectType, project);
}
gestionTraceability();
return projectsNewModel;
}
Found the solution, thanks to M. Deinum !
I needed to replace DriverManagerDataSource with a BasicDataSource in applicationContext :
DriverManagerDataSource create a new connection for each request wich is problematic when we want to send a lot of request.

Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException

I am quite new to Spring and Spring-Batch in particular.
Still I somehow managed to install the Spring Batch-Admin. I added custom jobs and Hibernate/JPA for persistence.
Everything is working as expected, up to the point where the first chunk should be persisted. Then I receive the following error-message:
org.springframework.transaction.CannotCreateTransactionException:
Could not open JPA EntityManager for transaction;
nested exception is java.lang.IllegalStateException: Already value
[org.springframework.jdbc.datasource.ConnectionHolder#60d31437]
for key [org.springframework.jdbc.datasource.DriverManagerDataSource#12da4b19]
bound to thread [jobLauncherTaskExecutor-1]
This is the full stacktrace:
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder#43f9e588] for key [org.springframework.jdbc.datasource.DriverManagerDataSource#84f171a] bound to thread [jobLauncherTaskExecutor-1]
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:427)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:335)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:105)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy41.saveIfUnique(Unknown Source)
at com.qompa.batch.ArticleItemWriter.write(ArticleItemWriter.java:28)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.writeItems(SimpleChunkProcessor.java:171)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.doWrite(SimpleChunkProcessor.java:150)
at org.springframework.batch.core.step.item.FaultTolerantChunkProcessor$3.doWithRetry(FaultTolerantChunkProcessor.java:313)
at org.springframework.batch.retry.support.RetryTemplate.doExecute(RetryTemplate.java:240)
at org.springframework.batch.retry.support.RetryTemplate.execute(RetryTemplate.java:187)
at org.springframework.batch.core.step.item.BatchRetryTemplate.execute(BatchRetryTemplate.java:213)
at org.springframework.batch.core.step.item.FaultTolerantChunkProcessor.write(FaultTolerantChunkProcessor.java:402)
at org.springframework.batch.core.step.item.SimpleChunkProcessor.process(SimpleChunkProcessor.java:194)
at org.springframework.batch.core.step.item.ChunkOrientedTasklet.execute(ChunkOrientedTasklet.java:74)
at org.springframework.batch.core.step.tasklet.TaskletStep$ChunkTransactionCallback.doInTransaction(TaskletStep.java:386)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130)
at org.springframework.batch.core.step.tasklet.TaskletStep$2.doInChunkContext(TaskletStep.java:264)
at org.springframework.batch.core.scope.context.StepContextRepeatCallback.doInIteration(StepContextRepeatCallback.java:76)
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:367)
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:214)
at org.springframework.batch.repeat.support.RepeatTemplate.iterate(RepeatTemplate.java:143)
at org.springframework.batch.core.step.tasklet.TaskletStep.doExecute(TaskletStep.java:250)
at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:195)
at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:135)
at org.springframework.batch.core.job.flow.JobFlowExecutor.executeStep(JobFlowExecutor.java:61)
at org.springframework.batch.core.job.flow.support.state.StepState.handle(StepState.java:60)
at org.springframework.batch.core.job.flow.support.SimpleFlow.resume(SimpleFlow.java:144)
at org.springframework.batch.core.job.flow.support.SimpleFlow.start(SimpleFlow.java:124)
at org.springframework.batch.core.job.flow.FlowJob.doExecute(FlowJob.java:135)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:281)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Caused by: java.lang.IllegalStateException: Already value [org.springframework.jdbc.datasource.ConnectionHolder#43f9e588] for key [org.springframework.jdbc.datasource.DriverManagerDataSource#84f171a] bound to thread [jobLauncherTaskExecutor-1]
at org.springframework.transaction.support.TransactionSynchronizationManager.bindResource(TransactionSynchronizationManager.java:189)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:402)
... 36 more
The same Job executes fine in a standalone application. The problem occurs only in the Spring-Batch-Admin environment. Below you can see the project structure and dependencies:
This is the app-context.xml that overrides/extends the Batch-Admin configuration:
<?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:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package="com.company.batch" />
<context:property-placeholder location="classpath:batch.properties" />
<import resource="classpath:/META-INF/spring/batch/jobs/article-job.xml" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${batch.jdbc.driver}" />
<property name="url" value="${batch.jdbc.url}" />
<property name="username" value="${batch.jdbc.user}" />
<property name="password" value="${batch.jdbc.password}" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.qompa.batch" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL"></property>
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
<property name="databasePlatform" value="com.company.utils.persistence.CustomPGDialect" />
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto"></prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<!-- schedule tasks -->
<task:scheduled-tasks>
<task:scheduled ref="articleRetrieval" method="run"
cron="0 0 */4 * * *" />
<task:scheduled ref="articleConversion" method="run"
cron="0 15 */4 * * *" />
</task:scheduled-tasks>
</beans>
What I understand so far is that it has to do with the ThreadPoolTaskExecutor to which the jobLauncherTaskExecutor bean refers. It seems to handle connection pooling for concurrently running jobs ... but to be honest I have no clue how to change my configurations to make these things work.
[Edit]: I am not even sure wether it is the afromentioned ThreadPoolTaskExecutor. But it seem s to be an implementation of the TaskExecutor interface.
If anyone ran into a similar issue, or has a suggestion how to configure my application in a way that transactions can be created for my persistence methods: Please give me a hint!
The error comes from JpaTransactionManager line 403:
TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
The error means that the transaction manager is trying to bind the datasource (not the entity manager) to the thread, but the datasource is already there and this is unexpected.
Note that the transaction manager had not started yet to bind the Entity Manager to the thread, that would happen next at JpaTransactionManager line 416:
There are two possible explanations:
Somebody (another transaction manager?) is adding the datasource to the thread before the transaction manager and this is unexpected.
Or no one is adding the datasource to the transaction manager, is just that at the end of the task execution no one cleans the thread before returning it to the pool, maybe due an error or an unhandled exception.
One question, does this also happen for only one execution thread, or only when there are several?
To find out what the problem is, these are some steps:
run with a minimal number of threads that cause the problem
put a breakpoint in TransactionSynchronizationManager.bindResource() to see who adds the connection to the thread. The breakpoint can be a conditional breakpoint with a condition on the thread name: "jobLauncherTaskExecutor-1".equals(Thread.currentThread().getName())
put also a breakpoint in TransactionSynchronizationManager.unbindResource(), to see if the datasource is unbound from the thread. when the breakpoints hit, scroll down the stacktrace and see which classes are causing this.
This normally happens when you have multiple transaction managers in place.
Some hints..
When using annotaion #EnableBatchProcessing, Spring Batch automatically registers a transaction manager , and your JpaTransactionManager may never get used.
If you want to change the transaction manager that spring batch uses, you have to implement the interface BatchConfigurer.(https://blog.codecentric.de/en/2013/06/spring-batch-2-2-javaconfig-part-3-profiles-and-environments/).
You can specify transaction manager for tasklets as follows:
<tasklet transaction-manager="transactionManager">
If you have 2 dataSource, I suggest you to read:
https://github.com/spring-projects/spring-boot/issues/3012
So... configure the main datasource (is important the transaction manager's name)
#Configuration
#EnableJpaRepositories(
entityManagerFactoryRef = "entityManager",
transactionManagerRef = "transactionManager",
basePackages = "a.b.c")
#PropertySource({"classpath:db_persistence.properties"})
#EnableTransactionManagement
and the other datasource:
#Configuration
#EnableJpaRepositories(
entityManagerFactoryRef = "another_EntityManager",
transactionManagerRef = "another_transactionManager",
basePackages = "x.y.z")
#PropertySource({"classpath:db_persistence.properties"})
#EnableTransactionManagement
I hope that this help you.
return stepBuilderFactory.get("orderStep1").<sourceBean, destBean>chunk(5)
.reader(reader)
.processor(batchFileRowProcessor)
.writer(batchFileRowDataWritter)
.taskExecutor(taskExecutor)
.transactionManager(platformTransactionManager)
.throttleLimit(1).build();
platformTransactionManager is the qualified bean from the data source configuration
I was able to solve a similar issue by implementing a spring batch configuration for JPA
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.BatchConfigurationException;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.explore.support.JobExplorerFactoryBean;
import org.springframework.batch.core.explore.support.MapJobExplorerFactoryBean;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean;
import org.springframework.batch.support.transaction.ResourcelessTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;
#Configuration
public class JpaBatchConfigurer implements BatchConfigurer {
private static final Logger logger = LoggerFactory
.getLogger(JpaBatchConfigurer.class);
#Inject
private DataSource dataSource;
#Inject
private PlatformTransactionManager transactionManager;
private JobRepository jobRepository;
private JobLauncher jobLauncher;
private JobExplorer jobExplorer;
protected JpaBatchConfigurer() {
}
#Override
#Bean
public JobRepository getJobRepository() {
return jobRepository;
}
#Override
public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
#Override
#Bean
public JobLauncher getJobLauncher() {
return jobLauncher;
}
#Override
#Bean
public JobExplorer getJobExplorer() {
return jobExplorer;
}
#PostConstruct
public void initialize() {
try {
if (dataSource == null) {
logger.warn("No datasource was provided...using a Map based JobRepository");
if (this.transactionManager == null) {
this.transactionManager = new ResourcelessTransactionManager();
}
MapJobRepositoryFactoryBean jobRepositoryFactory = new MapJobRepositoryFactoryBean(
this.transactionManager);
jobRepositoryFactory.afterPropertiesSet();
this.jobRepository = jobRepositoryFactory.getObject();
MapJobExplorerFactoryBean jobExplorerFactory = new MapJobExplorerFactoryBean(
jobRepositoryFactory);
jobExplorerFactory.afterPropertiesSet();
this.jobExplorer = jobExplorerFactory.getObject();
} else {
this.jobRepository = createJobRepository();
JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
jobExplorerFactoryBean.setDataSource(this.dataSource);
jobExplorerFactoryBean.afterPropertiesSet();
this.jobExplorer = jobExplorerFactoryBean.getObject();
}
this.jobLauncher = createJobLauncher();
} catch (Exception e) {
throw new BatchConfigurationException(e);
}
}
private JobLauncher createJobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor( new SimpleAsyncTaskExecutor());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
protected JobRepository createJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setIsolationLevelForCreate("ISOLATION_SERIALIZABLE");
factory.setDataSource(dataSource);
factory.setTransactionManager(transactionManager);
factory.setValidateTransactionState(false);
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public JobBuilderFactory jobBuilderFactory(JobRepository jobRepository){
return new JobBuilderFactory(jobRepository);
}
#Bean
public StepBuilderFactory stepBuilderFactory(JobRepository jobRepository, PlatformTransactionManager transactionManager){
return new StepBuilderFactory(jobRepository, transactionManager);
}
}
This was copied from:https://github.com/hantsy/spring4-sandbox/blob/master/batch-jpa/src/main/java/com/hantsylabs/example/spring/config/JpaBatchConfigurer.java
These kind of problems occur with older version of java like jdk 6 or further lower versions.Upgrade your jdk version to 7 or above. Even i do had the same kinda issue before which gone when i updated my jdk version to 7.

Categories

Resources