I'm new in Java! When I run the Junit test the console show me exception and I don't know how to resolve this. What is wrong with my Hibernate configuration? This code perfect works with H2 database, but when I change database and config parameters to Mysql 8.0 the Eclipse return exception. I hope that someone can give me useful advice and explain how resolve this problem. Thanks.
This is my Hibernate Configuration for Mysql 8.0
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#ComponentScan(basePackages= {"com.savaleks.websiteback.dto"})
#EnableTransactionManagement
public class HibernateConfig {
private final static String DATABASE_URL = "jdbc:mysql://localhost:3306/website";
private final static String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private final static String DATABASE_DIALECT = "org.hibernate.dialect.MySQL8Dialect";
private final static String DATABASE_USERNAME = "root";
private final static String DATABASE_PASSWORD = "";
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
// Database connection information
dataSource.setDriverClassName(DATABASE_DRIVER);
dataSource.setUrl(DATABASE_URL);
dataSource.setUsername(DATABASE_USERNAME);
dataSource.setPassword(DATABASE_PASSWORD);
return dataSource;
}
#Bean
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
builder.addProperties(getHibernateProperties());
builder.scanPackages("com.savaleks.websiteback.dto");
return builder.buildSessionFactory();
}
// All Hibernate properties returned in this method
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", DATABASE_DIALECT);
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return null;
}
#Bean
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
And this is console output
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'categoryDAO': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in com.savaleks.websiteback.config.HibernateConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Factory method 'getSessionFactory' threw exception; nested exception is java.lang.NullPointerException
pom.xml file
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.20.RELEASE</spring.version>
<mysql.version>8.0.13</mysql.version>
<hibernate.version>5.2.17.Final</hibernate.version>
</properties>
<dependencies>
<!-- JUNIT TEST -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- SPRING CONTEXT -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- MYSQL DATABASE -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- HIBERNATE -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- DATABASE CONNECTION POOLING -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
If need more information, I can load more classes and console output. What could be wrong? any ideas?
Change to:
#Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(getSessionFactory());
return transactionManager;
}
or,
#Bean
public HibernateTransactionManager getTransactionManager(#Qualifier("getSessionFactory") SessionFactory sessionFactory) {
// your code here
}
or,
#Bean
public SessionFactory sessionFactory(DataSource dataSource) {
// your code here
}
There are few more ways.
Further Reading:
#Bean Methods in #Configuration Classes paragraph in Spring Framework javadoc of #Bean.
1.12.1. Basic Concepts: #Bean and #Configuration in Spring Framework Reference (version 5.1.3.RELEASE)
Related
Then I build and dismantle my project in several ways, I find this error which has me stuck from one moment to the next started to come out and tells me that I can't import one of the java configuration files (the one for Hibernate).
The project is composed of a .ear, which contains a .jar, a .ejb and the web application.
Please help with the following error:
ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "ear-1.0.0.ear")]) - failure description: {"WFLYCTL0080: Failed services" => {"jboss.deployment.subunit.\"ear-1.0.0.ear\".\"web-1.0.0.war\".undertow-deployment" => "java.lang.RuntimeException: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.creatics.minstituto.config.HibernateConfig]; nested exception is java.lang.IllegalArgumentException: class org.springframework.context.annotation.AutoProxyRegistrar is not assignable to interface org.springframework.context.annotation.ImportBeanDefinitionRegistrar
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.creatics.minstituto.config.HibernateConfig]; nested exception is java.lang.IllegalArgumentException: class org.springframework.context.annotation.AutoProxyRegistrar is not assignable to interface org.springframework.context.annotation.ImportBeanDefinitionRegistrar
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.creatics.minstituto.config.HibernateConfig]; nested exception is java.lang.IllegalArgumentException: class org.springframework.context.annotation.AutoProxyRegistrar is not assignable to interface org.springframework.context.annotation.ImportBeanDefinitionRegistrar
Caused by: java.lang.IllegalArgumentException: class org.springframework.context.annotation.AutoProxyRegistrar is not assignable to interface org.springframework.context.annotation.ImportBeanDefinitionRegistrar"}}
These are the spring and hibernate libraries of the pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.10.Final</version>
</dependency>
This is my SpringInitializer:
public class SpringInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
// Load database and spring security configuration
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { HibernateConfig.class, SpringSecurityConfig.class };
}
// Load spring web configuration
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
This is my HibernateConfig
#Configuration
#PropertySource({ "classpath:application.properties", "classpath:hibernate.properties" })
#EnableTransactionManagement
#ComponentScans(value = {
#ComponentScan("com.creatics.dao"), #ComponentScan("com.creatics.minstituto.dao"),
#ComponentScan("com.creatics.service"), #ComponentScan("com.creatics.minstituto.service")
})
public class HibernateConfig {
#Value("${metadata.jndi}")
private String metadataJNDI;
#Value("${hibernate.dialect}")
private String dialect;
#Value("${hibernate.show_sql}")
private String showSql;
#Value("${hibernate.hbm2ddl.auto}")
private String hbm2ddlAuto;
#Value("${hibernate.c3p0.min_size}")
private String c3p0MinSize;
#Value("${hibernate.c3p0.max_size}")
private String c3p0MaxSize;
#Value("${hibernate.c3p0.acquire_increment}")
private String c3p0AcquireIncrement;
#Value("${hibernate.c3p0.timeout}")
private String c3p0Timeout;
#Value("${hibernate.c3p0.max_statements}")
private String c3p0MaxStatements;
#Bean
public HibernateTransactionManager getTransactionManager() throws Exception {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory());
return transactionManager;
}
#Bean
public SessionFactory getSessionFactory() throws Exception {
LocalSessionFactoryBuilder sessionFactoryBuilder = new LocalSessionFactoryBuilder(getDataSource());
sessionFactoryBuilder.scanPackages("com.creatics.minstituto.model");
sessionFactoryBuilder.addProperties(getHibernateProperties());
return sessionFactoryBuilder.buildSessionFactory();
}
#Bean
public DataSource getDataSource() throws Exception {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
dataSourceLookup.setResourceRef(true);
return dataSourceLookup.getDataSource(metadataJNDI);
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put(DIALECT, dialect);
properties.put(SHOW_SQL, showSql);
properties.put(HBM2DDL_AUTO, hbm2ddlAuto);
properties.put(C3P0_MIN_SIZE, c3p0MinSize);
properties.put(C3P0_MAX_SIZE, c3p0MaxSize);
properties.put(C3P0_ACQUIRE_INCREMENT, c3p0AcquireIncrement);
properties.put(C3P0_TIMEOUT, c3p0Timeout);
properties.put(C3P0_MAX_STATEMENTS, c3p0MaxStatements);
return properties;
}
}
this is hibernate.properties:
## jndi Properties
metadata.jndi = java:/PostgresDS/database
## Hibernate Properties
hibernate.dialect = org.hibernate.dialect.PostgreSQL95Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=validate
#C3P0 properties
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=1
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=150
I try to create Spring data jpa program without SpringBoot.
Configuration class:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"springdata.repository"})
#ComponentScan(basePackages = {"springdata.entities.service"})
#PropertySource("classpath:data.properties")
public class SpringDataConfig {
#Autowired
private Environment env;
#Bean
public DataSource dataSource() {
final BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setUrl(env.getProperty("jdbc.url"));
basicDataSource.setUsername(env.getProperty("jdbc.user"));
basicDataSource.setPassword(env.getProperty("jdbc.password"));
return basicDataSource;
}
#Bean
public Properties hibernateProperties() {
final Properties hibernateProp = new Properties();
hibernateProp.put("hibernate.dialect", "org.hibernate.H2Dialect");
hibernateProp.put("hibernate.format_sql", true);
hibernateProp.put("hibernate.use_sql_comments", true);
hibernateProp.put("hibernate.show_sql", true);
hibernateProp.put("hibernate.hbm2ddl.auto", "update");
hibernateProp.put("hibernate.max_fetch_depth", 3);
hibernateProp.put("hibernate.jdbc.batch_size", 10);
hibernateProp.put("hibernate.jdbc.fetch_size", 50);
return hibernateProp;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
return new HibernateJpaVendorAdapter();
}
#Bean
public PlatformTransactionManager transactionManager(final EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(final JpaVendorAdapter jpaVendorAdapter,
final Properties hibernateProperties,
final DataSource dataSource) {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPackagesToScan("springdata.entities");
em.setDataSource(dataSource);
em.setJpaVendorAdapter(jpaVendorAdapter);
em.setJpaProperties(hibernateProperties);
em.afterPropertiesSet();
return em;
}
}
Test class:
public class Test {
public static void main(final String[] args) throws SQLException {
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringDataConfig.class);
DuckService duckService = ctx.getBean(DuckService.class);
System.out.println(duckService.findAll().size());
}
}
maven dependency:
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.4.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.8.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>6.1.0.Alpha2</version>
</dependency>
</dependencies>
And there are exception:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in springdata.SpringDataConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
I try to find decision of this proplem, and on SO was similar question, and solution was to replace javax.persistance on hibernate.javax.persistance. But in my case, I have new exception.
Change hibernate dialect
hibernateProp.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
I create a project with Spring and when I compile I got this errors with Controller and entityManagerFactory. This is my first project with Spring and I don`t know what is wrong. Could you help me?
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeesController': Unsatisfied dependency expressed through field 'employeeRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'employeeRepository': Cannot create inner bean '(inner bean)#2996c83d' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2996c83d': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/pszymanski/config/DBConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
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:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:540)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:992)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4921)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5231)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:752)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:728)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:596)
at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1805)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:506)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:405)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1595)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:280)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:123)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1184)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1412)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1380)
at java.lang.Thread.run(Thread.java:745)
pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
<groupId>pszymanski</groupId>
<artifactId>employees</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>4.3.7.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.11.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
<!---Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.12.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.12.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.2.Final</version>
</dependency>
<!-- Mysql Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
Database Configuration:
#Configuration
#PropertySource(value = {"classpath:db.properties"})
#EnableJpaRepositories(basePackages = {"com.pszymanski.repository"})
public class DBConfig {
#Autowired
private Environment environment;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driver.class.name")); //hibernate configuration for database
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.user.name"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager() {
EntityManagerFactory factory = entityManagerFactory();
return new JpaTransactionManager(factory);
}
#Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(Boolean.TRUE);
vendorAdapter.setShowSql(Boolean.TRUE);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.pszymanski.model");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return factory.getObject();
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
EmployeeController:
package com.pszymanski.controller;
import com.pszymanski.model.Employee;
import com.pszymanski.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;
import java.util.List;
#Controller
public class EmployeesController {
#Autowired
private EmployeeRepository employeeRepository;
#RequestMapping(value = "/employees", method = RequestMethod.GET)
public String getEmployeesPage(Model model) {
List<Employee> employeeList = employeeRepository.findAll();
model.addAttribute("employeesList", employeeList);
return "employees";
}
#RequestMapping(value = "/employees-add", method = RequestMethod.GET)
public String addEmployee(Model model) {
model.addAttribute("employees", new Employee());
return"employees-add";
}
#RequestMapping(value = "/employees-add/save", method = RequestMethod.POST)
public String saveEmployee( #ModelAttribute #Valid Employee employee, BindingResult result) {
if(result.hasErrors()) {
return "employees-add";
}
employeeRepository.save(employee);
return"redirect:/employees";
}
#RequestMapping(value = "/employees-add/cancel", method = RequestMethod.GET)
public String cancel() {
return "redirect:/employees";
}
#RequestMapping(value = "/employees/edit/{id}", method = RequestMethod.GET)
public String editEmployee(#PathVariable Long id, Model model){
Employee employee = employeeRepository.findOne(id);
model.addAttribute("employee", employee);
return "employee-add";
}
#RequestMapping(value ="/employees/delete/{id}", method = RequestMethod.POST)
public String deleteEmployee(#PathVariable Long id) {
employeeRepository.delete(id);
return "redirect:/employees";
}
}
EmployeeRepository:
package com.pszymanski.repository;
import com.pszymanski.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
}
See this article for an example. You are returning an EntityManagerFactory in your java config rather than the LocalContainerEntityManagerFactoryBean.
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.baeldung.persistence.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
Just return the factory, not factory.getObject().
I am getting this error when I run my spring-mvc application :
Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
Error creating bean with name 'personDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.PersonDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
I have also checked the dependencies in my pom.xml
<!-- Spring -->
<spring-framework.version>4.2.4.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>5.2.1.Final</hibernate.version>
Apart from this, I have specified ${spring-framework.version} and ${hibernate.version} in the version of all the dependencies
//////////////////////////////Spring Configuration//////////////
package com.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.model.Person;
import com.service.PersonService;
#Configuration
#EnableWebMvc
#ComponentScan({ "com.*" })
#EnableTransactionManagement
public class SpringConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment environment;
#Autowired
private PersonService ps;
#Bean #Autowired
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setAnnotatedClasses(Person.class);
sessionFactory.setPackagesToScan(new String[] { "com.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean #Autowired
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
dataSource.setUsername("root");
dataSource.setPassword("admin123");
return dataSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/*");
}
#Bean #Autowired
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver res = new InternalResourceViewResolver();
res.setPrefix("/WEB-INF/view/");
res.setSuffix(".jsp");
return res;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.search.default.directory_provider", "org.hibernate.search.store.impl.FSDirectoryProvider");
properties.put("hibernate.search.default.indexBase", "H:/MyWorkspace/MainAssignment3/indexes");
return properties;
}
#Bean #Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
///////////////////////////////////POM////////////////////////////////
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples.service.service</groupId>
<artifactId>MainAssignment3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Spring -->
<spring-framework.version>4.2.1.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>5.1.1.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version> </dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
<dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId>
<version>1.1</version> </dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.5.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-engine</artifactId>
<version>5.5.4.Final</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
///////////////////////////////DAO File//////////////////////////////
package com.dao;
import java.util.List;
import com.model.Person;
public interface PersonDAO {
public void save(Person p);
public List<Person> list();
public void updatePerson(Integer id);
public Person getPersonById(int id);
public void removePerson(Integer id);
public void indexPersons() throws Exception;
public List<Person> searchForPerson(String searchText) throws Exception;
}
//////////////////////////DAO Impl///////////////////////////
package com.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.model.Person;
#Transactional
#Repository
public class PersonDAOImpl implements PersonDAO, java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = (Logger) LoggerFactory
.getLogger(PersonDAOImpl.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
public void save(Person p) {
// TODO Auto-generated method stub
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(p);
tx.commit();
s.close();
System.out.println("Record successfully inserted");
}
#SuppressWarnings("deprecation")
public List<Person> list() {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
#SuppressWarnings("unchecked")
List<Person> personsList = session.createQuery("from Person").list();
for (Person p : personsList) {
logger.info("Person List::" + p);
}
return personsList;
}
public void updatePerson(Integer id) {
Session session = new Configuration().configure().buildSessionFactory()
.openSession();
Person p = new Person();
Person person = session.get(Person.class, p.getId());
//Transaction t = session.beginTransaction();
Query query = session.createQuery("from Person");
person.setName(p.getName()); // modify the loaded object somehow
session.update(person);
//t.commit();
session.close();
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details=" + p);
return p;
}
public void removePerson(Integer id) {
Session session = sessionFactory.getCurrentSession();
// Transaction t = session.beginTransaction();
Person p = (Person) session.load(Person.class, new Integer(id));
session.delete(p);
// t.commit();
logger.info("Person deleted successfully, person details=");
}
#Transactional
public void indexPersons() throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
}
catch(Exception e)
{
throw e;
}
}
public List<Person> searchForPerson(String searchText) throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder qb = fullTextSession.getSearchFactory()
.buildQueryBuilder().forEntity(Person.class).get();
org.apache.lucene.search.Query query = qb
.keyword().onFields("name", "address", "salary","gender")
.matching(searchText)
.createQuery();
org.hibernate.Query hibQuery =
fullTextSession.createFullTextQuery(query, Person.class);
List<Person> results = hibQuery.list();
return results;
}
catch(Exception e)
{
throw e;
}
}
}
According to docs you should update your Spring dependency to 4.3 if you want to use Hibernate 5.2.
Also you have to correct dependencies for Hibernate search (it's releases are different then Hibernate's core).
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.5.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-engine</artifactId>
<version>5.5.4.Final</version>
</dependency>
I am trying to use arquillian-persistence-dbunit where I have to seed the database with datas but none of my solutions work. My project is based on Spring and we are using JavaConfig.
In my POM, I have the arquillian jars :
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.1.10.Final</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<!-- Arquillian dependencies -->
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-persistence-dbunit</artifactId>
<version>1.0.0.Alpha7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-service-integration-spring-inject</artifactId>
<version>1.1.0.Alpha1</version>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-service-integration-spring-javaconfig</artifactId>
<version>1.1.0.Alpha1</version>
</dependency>
My test class :
#RunWith(Arquillian.class)
#Transactional(PersistanceTestConfig.TRANSACTION_NAME)
#SpringAnnotationConfiguration(classes = {ArquillianConfiguration.class})
#DataSource(PersistanceTestConfig.MY_DATASOURCE)
#UsingDataSet({"database/myDataset.yml"})
public class MyTestClass{
#Deployment(testable = false)
public static WebArchive createArchive(){
//returns a webArchive
}
#Test
public void myTestMethod(){
//do something
}
}
My config classes :
#Configuration
#Import({PersistanceTestConfig.class})
#ComponentScan(basePackages = {"com.myapp.dao", ""com.myapp.services"})
#EnableCaching
#EnableTransactionManagement
public class ArquillianConfiguration {}
And the PersistenceTestConfig :
public class PersistanceTestConfig {
public static final String TRANSACTION_NAME = "transaction";
public static final String MY_DATASOURCE = "datasource";
private Properties getJPAProperties() {
final Properties jpaProperties = new Properties();
jpaProperties.setProperty("hibernate.hbm2ddl.auto", "create");
jpaProperties.setProperty("hibernate.show_sql", "true");
jpaProperties.setProperty("hibernate.format_sql", "true");
jpaProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
return jpaProperties;
}
#Bean(name = MY_DATASOURCE)
public DataSource getDataSource(){
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
.continueOnError(false).ignoreFailedDrops(true).build();
}
#Bean
#Autowired
public LocalContainerEntityManagerFactoryBean getEntityManagerREFCS( DataSource dataSource) {
final LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
localContainerEntityManagerFactoryBean.setDataSource(dataSource);
localContainerEntityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
localContainerEntityManagerFactoryBean.setPackagesToScan("com.myapp.dao.beans");
localContainerEntityManagerFactoryBean.setPersistenceUnitName("pUnitName");
localContainerEntityManagerFactoryBean.setJpaProperties(getJPAProperties());
return localContainerEntityManagerFactoryBean;
}
}
I have tried many solutions, but I still have the same error :
org.jboss.arquillian.transaction.impl.lifecycle.TransactionProviderNotFoundException: Transaction provider for given test case has not been found.
What bothers me is there are not so many documentations on how to use arquillian-persistence-dbunit with JavaConfig. The only example that I see are badsed on xml configuration only. For instance, in this project.
Has Anyone used arquillian-persistence-dbunit with JavaConfig.