Create HibernateJpaVendorAdapter instance failed. Why? - java

I created a spring JPA example according to "Spring in Action", chapter 11.
Java config code:
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
System.out.println("hello");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
System.out.println(adapter);
adapter.setDatabase(Database.MYSQL);
adapter.setShowSql(true);
adapter.setGenerateDdl(false);
adapter.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
return adapter;
}
#Bean
public EntityManagerFactory entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource);
//emfb.setPersistenceUnitName("test");
emfb.setJpaVendorAdapter(jpaVendorAdapter);
emfb.setPackagesToScan("com.springinaction.test");
EntityManagerFactory emf = emfb.getObject();
System.out.println(emf);
return emf;
}
#Bean
public PlatformTransactionManager annotationDrivenTransactionManager(EntityManagerFactory emf) {
//System.out.println(emf);
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
Maven dependencies associated with Spring JPA:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
The program runs fine up to this line of code:
System.out.println("hello");
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
and fails with below error message:
hello
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class com.springinaction.test.JdbcConfig: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.orm.jpa.JpaVendorAdapter com.springinaction.test.JdbcConfig.jpaVendorAdapter()] threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/ejb/HibernatePersistence
Someone said to me that the reason could be the absence of hibernate-entitymanger.jar, but I find this jar in local Maven repository.
And someone says that reason is missing ejb3-persistence.jar, but I couldn't find the Maven groupId/artifactId for this.
Can someone please explain this to me?

Class org.hibernate.ejb.HibernatePersistence is part of hibernate-entitymanager jar. Please check if this jar is in your project class path or in deployed war file. Also check the version of this jar file.Instead of providing hibernate-core and hibernate-jpa you should provide hibernate-entitymanager dependency in pom.xml and this will download all the required dependencies. You can check the same at https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager/5.2.2.Final
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.2.Final</version>
</dependency>
The source code for Spring In Action is at https://manning-content.s3.amazonaws.com/download/9/ef4e0ef-b7bd-4ab8-857d-eb635d18d425/SpringiA4_SourceCode.zip. You can check the build.gradle file for dependency used.

Related

Caused by: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName

My spring boot test is throwing the below error during maven build.
"level":"ERROR","logger":"com.zaxxer.hikari.HikariConfig","msg":"HikariPool-1 - jdbcUrl is required with driverClassName."
Stacktrace:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'schedulerFactoryBean' defined in class path resource
[com/pit/SchedulerConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: jdbcUrl is requir
ed with driverClassName.
Caused by: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
The method that throws an error in my MyApplicationTest.java
#SpringBootTest
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#EnableConfigurationProperties(value = MyConfig.class)
class MyApplicationTest {
#Test
void contextLoads() {
assertNotNull(myController);
}
}
My pom has these dependencies in classpath.
spring-boot-starter-web
spring-boot-starter-test
spring-integration-sftp
postgresql
junit
quartz-scheduler
My Datasource bean is configured as below
#Configuration
public class MyDataSourceCfg {
private DataSource appDataSource() {
return DataSourceBuilder.create()
.driverClassName("org.postgresql.Driver")
.url(env.getProperty("url") // values are set from Environment
.username(env.getProperty("user"))
.password(env.getProperty("password")
.build();
}
}
Please tell me what is happening and how I avoid this error. I read about configuring Datasource in different way in case you have multiple database but I just have one postgres database. Please share your thoughts.
Considering that you have all relevant dependencies.
as Connect to PostgreSQL Database with Spring Data JPA such as :-
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
and in application.properties file:
spring.datasource.url=jdbc:postgresql://localhost:5432/dev
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
With SpringBoot's powerful autoconfiguration, you don't need to explicitly create a DataSource bean and if in case you want, use these properties values.

Spring bootb absctractmethoderror after hibernate upgrade

My project use spring boot 1.3.8 and now I have to upgrade hibernate from 4.* to 5.*. When I add dependencies and start project I have error "java.lang.AbstractMethodError" after initialization Datasource bean. What can I do for resolve this problem ?
#Bean
public LocalContainerEntityManagerFactoryBean ussdDBEntityManagerFactory(final EntityManagerFactoryBuilder builder) {
LocalContainerEntityManagerFactoryBean emf = builder
.dataSource(ussdDBDataSource())
.persistenceUnit("ussdDBPersistenceUnit")
.build();
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "none");
emf.setJpaProperties(properties);
return emf;
}
Error: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ussdDBEntityManagerFactory' defined in class path resource [com/intech/kievstar/config/DBUssdConfiguration.class]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
Solution of my problem was dependency:
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>5.0.0.GA</version>
</dependency>
When I up verson to 5.0.0.GA, problem was resolved

spring-boot web app fails to start : Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

I'm trying to start my spring-boot-web app but I'm getting the following error :
2020-03-17 20:54:22.643 WARN 15640 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
2020-03-17 20:54:22.664 ERROR 15640 --- [ main] o.s.boot.SpringApplication : Application run failed
I configured the following ApplicationContext file :
#Configuration
#EnableJpaRepositories(basePackages = {"repos"})
public class AppConfig {
#Bean
public LocalEntityManagerFactoryBean entityManagerFactory() {
LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean();
factoryBean.setPersistenceUnitName("mydb");
return factoryBean;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
I need those beans because in one of my services I inject the following objects :
#Autowired
private EntityManagerFactory emf;
#PersistenceContext
private EntityManager em;
and my main app :
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[]args)
{
//load the spring config class we configured
SpringApplication.run(AppConfig.class);
}
my dependencies in pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.11</version>
</dependency>
Solutions I tried but didnt work :
1)add extends SpringBootServletInitializer to both Application.java and Appconfig.java
2)Move the beans from the AppConfig.java to Application.java
3)Tried to set the following annotation on the application class :
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
4)Adding the following dependency to the pom.xml :
org.springframework.boot
spring-boot-starter-tomcat
2.2.5.RELEASE
I resolved my problem by adding dependancy 'spring-boot-starter-web'.
Make sure that your filename, class name and the name of the class inside the SpringApplication.run() function are the same.
Also, make sure you haven't forgotten the #SpringBootApplication annotation.
My solution :
In addition to the persistence.xml file I created application.properties file :
# Connection url for the database
spring.datasource.url=jdbc:postgresql://ip:port/db
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto =update
spring.jpa.show-sql = true
chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL9Dialect
spring.jpa.generate-ddl=true
server.port = 9091
Afterwards, in my Application.java I added the following annotations and extend :
#SpringBootApplication
#EnableJpaRepositories("repositories")
#EntityScan("dao")
public class Application extends SpringBootServletInitializer {
You can comment the <scope>provided</scope> in pom.xml file like below
You need to override configure method from SpringBootServletInitializer
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}

Configure JPA/Hibernate/PostgreSQL without XML

I'm getting back into the Java world, and I'm trying to configure a new Spring web application with JPA, Hibernate and PostgreSQL.
I have found a lot of older examples with various XML configuration files, and I'm wondering if there is a preferred new way to perform this configuration without relying on XML file authoring.
Some of the things I need to configure are the hibernate sql dialect, driver, etc.
Put the following fragments into a class annotated with #Configuration and #EnableTransactionManagement
Hibernate/JPA (edit the packagesToScan String):
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.XY.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect");
properties.setProperty("hibernate.show_sql", "true");
return properties;
}
DataSource (edit username, password and host address):
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:port/DB_NAME");
dataSource.setUsername("root");
dataSource.setPassword("");
return dataSource;
}
Transaction Manager:
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
If you're gonna use spring, i recommend to use Spring Boot which offers many auto configurations. you can use a application.properties for configuring dialects and stuff:
spring.datasource.url = <jdbcurl>
spring.datasource.username = <username>
spring.datasource.password = <password>
spring.datasource.driver-class-name = org.postgresql.Driver
Spring Boot provides a number of Starter Packages that make easy to add jars to your classpath. These Starter Packages simply provide dependencies that you are likely to need when developing a specific type of application. Since you're developing a possibly web application that requires data access, you should add these to your pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.1.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
Basically, spring boot tries to guess how you will want to configure your application, based on the jar dependencies that you have added. spring-boot-starter-data-jpa, provides the following key dependencies:
Hibernate — One of the most popular JPA implementations.
Spring Data JPA — Makes it easy to implement JPA-based repositories.
Spring ORMs — Core ORM support from the Spring Framework.
You can explicitly configure JPA settings using spring.jpa.* properties. For example, to create and drop tables you can add the following to your application.properties:
spring.jpa.hibernate.ddl-auto=create-drop
You can read more about spring boot here

java.lang.NullPointerException at org.apache.tiles.access.TilesAccess.getContainer(TilesAccess.java:124)

I do have all jars of spring 4.1.7 and tiles 3.0.5 version jars,
Please find below error .
SCHWERWIEGEND: Servlet.service() for servlet [mccstore] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'standard_welcome': Invocation of init method failed; nested exceptio
n is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.apache.tiles.access.TilesAccess.getContainer(TilesAccess.java:124)
at org.apache.tiles.access.TilesAccess.getContainer(TilesAccess.java:107)
at org.springframework.web.servlet.view.tiles3.TilesView.afterPropertiesSet(TilesView.java:97)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
Make sure you have defined the following beans:
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tiles = new TilesConfigurer();
tiles.setDefinitions("/WEB-INF/definitions.xml");
return tiles;
}
#Bean
public UrlBasedViewResolver viewResolver() {
UrlBasedViewResolver tilesViewResolver = new UrlBasedViewResolver();
tilesViewResolver.setViewClass(TilesView.class);
return tilesViewResolver;
}
and have the following dependencies:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
Hope it helps.

Categories