Another unnamed CacheManager already exists when using Hibernate L2 ehcache and spring boot enabledCache - spring

I have an application that have more than 100 domain model i want to integrate ehcache and hibernate L2cache ,my application used ehcache for cache some of service s methods . my CacheConfiguration is like this
package org.roshan.framework.config;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;
#Configuration
#EnableCaching
#AutoConfigureAfter(value = {DatabaseConfiguration.class})
public class CacheConfiguration {
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;
#PreDestroy
public void destroy() {
log.info("Remove Cache Manager metrics");
log.info("Closing Cache Manager");
}
public CacheConfiguration(JHipsterProperties jHipsterProperties) {
JHipsterProperties.Cache.Ehcache ehcache = jHipsterProperties.getCache().getEhcache();
jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
ResourcePoolsBuilder.heap(ehcache.getMaxEntries()))
.withExpiry(Expirations.timeToLiveExpiration(Duration.of(ehcache.getTimeToLiveSeconds(), TimeUnit.SECONDS)))
.build()
);
}
#Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
log.debug("Starting Ehcache");
return cm -> {
// some cache for using in method of service
cm.createCache("baseInfoCache", jcacheConfiguration);
cm.createCache("attachments", jcacheConfiguration);
};
}
}
in application.yml change hibernate cache config like this
spring:
devtools:
restart:
enabled: true
livereload:
enabled: true # we use gulp + BrowserSync for livereload
application:
name: roshanframework
jpa:
open-in-view: true
hibernate:
ddl-auto: none
properties:
hibernate.cache.use_second_level_cache: true
hibernate.cache.use_query_cache: false
hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.generate_statistics: false
hibernate.dialect : org.hibernate.dialect.MySQL5Dialect
#hibernate.default_schema : ihsl
hibernate.show_sql : true
hibernate.current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
but when i start my application i get exception that i have 2 cachemanager how solve this problem .
The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
at org.hibernate.cache.ehcache.EhCacheRegionFactory.start(EhCacheRegionFactory.java:90)
at org.hibernate.cache.spi.RegionFactory.start(RegionFactory.java:63)
at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:71)
at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:28)
at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:20)
at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:58)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
... 45 common frames omitted
Caused by: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
at net.sf.ehcache.CacheManager.assertNoCacheManagerExistsWithSameName(CacheManager.java:626)
at net.sf.ehcache.CacheManager.init(CacheManager.java:391)
at net.sf.ehcache.CacheManager.<init>(CacheManager.java:269)
at org.hibernate.cache.ehcache.EhCacheRegionFactory.start(EhCacheRegionFactory.java:69)
... 51 common frames omitted
I dont know why two cache manager exist? how can change configuration to using one cache manager for both hibernate and methods?

I also ran into this problem recently.
Soln is to use "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory" as hibernate factory_class.
spring:
jpa:
properties:
hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory

Related

a bean of type 'org.springframework.mail.javamail.JavaMailSender' that could not be found

I am using spring boot 2.0.7 Release and spring-boot-starter-mail-2.0.7.Release.
I am autowiring javaMailsender inside the class working ok on windows while trying to deploy on Unix getting belwo issue
APPLICATION FAILED TO START
***************************
Description:
Field javaMailSender in com.fti.di.capstock.tran.pub.email.SendEmail required a bean of type 'org.springframework.mail.javamail.JavaMailSender' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.mail.javamail.JavaMailSender' in your configuration.
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;
import com.fti.di.capstock.tran.pub.constants.ApplicationFlowConstants;
import com.fti.di.integration.constants.IntegrationConstants;
import com.fti.di.integration.util.StringUtil;
#Component("sendEmail")
public class SendEmail {
#Autowired
private JavaMailSender javaMailSender;
#Autowired
Environment env;
#ServiceActivator
you've to provide the mail configuration in application.properties
spring.mail.host=MAIL_SERVER_IP
spring.mail.port=MAIL_SERVER_PORT
spring.mail.userName=USER_NAME
spring.mail.password=THE_PASSWORD
and if authentication not enable in server then
remove userName and password and add this
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=false
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
#Configuration
public class Config {
#Bean
public JavaMailSender javaMailSender() {
return new JavaMailSenderImpl();
}
}
You can also return an instance of JavaMailSenderImpl() from your #Bean above saving you the hustle of having to implement a bunch of methods when you try to return the actual JavaMailSender() class.
Declare a #Bean of the type JavaMailSender in a Configuration class (This is useful when you want to inject a class which is not part of your Spring Context, like a class that belongs to a 3rd-party lib, which happens to be your case). For example:
#Configuration
public class MyConfig {
#Bean
public JavaMailSender javaMailSender() {
return new JavaMailSender();
}
}
Make sure that the you have set the right properties under application.properties as well.
Also, take a look into this question, as I believe this is a duplicate (if it's not, I am sorry)
In My project i was reading email properties file like hostname, port etc from spring config server (Spring cloud).
I was missing a dependency at client end. Once i added that Dependency.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
JavamailSender class able to read those properties and worked fine.
In spring boot we need not define JavaMailSender bean manually. spring boot does itself.
the best answer I ve found was to check if you have a type in your application.properties:
spring.mail.host
spring.mail.username
spring.mail.password
spring.mail.port
Check the response of gleidson cardoso da silva from Could not autowire org.springframework.mail.javamail.JavaMailSender
This error occurred due to the missing following properties in the application.yml file.
mail:
host: localhost
port: 1025
username: hello
password: hello
properties:
mail:
smtp:
ssl:
trust: "*"
auth: true
starttls:
enable: true
connectiontimeout: 5000
timeout: 3000
writetimeout: 5000
I have this error and it was related to missing properties in application.yml in the test folder.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'environment' available

I am getting this following exception on my production while running my code. I don't know what I am making mistake, the same code is happily running on my local machine, please help
Feb 19 13:46:40 ip-10-0-77-139 server: ShopifyGetItems: Service
function shop.getShopifyDomain():
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'hibernateConfig': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'environment' available
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.webbee.app" })
#PropertySource(value = { "classpath:internal.properties" })
public class HibernateConfig {
#Autowired
private Environment environment;
private Properties hibernateProperties() {
System.out.println(environment.getRequiredProperty("hibernate.dialect"));
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.jdbc.batch_size", 1000); // batch size for save or update
return properties;
}
}
It will be good, if you can debug the issue -
System.out.println("Created beans: " + Arrays.toString(context.getBeanNamesForType(Environment.class)));
if you are getting empty list it means, your bean is not instantiated in spring container and there is some problem with component scan.
This helped me in spring boot 2.4 but not in 2.6
spring:
config:
use-legacy-processing: false

Spring boot Multi-module project multi-datasource

I'm trying to develop a multi-module spring boot project with multi-datasource connection. I have separate this project in 5 modules:
-springboot-multiple-maven-modules:
1. domain -> database2's model
2. domain2 -> database2's model
3. persistence -> database1's persistence
4. persistence2 -> database2's persistence
5. web -> Access to database1 and database2
You can download the code in the following link:
GitHub Project
I've configure both datasource in this way:
- database1:
package rc.persistence;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "hotelEntityManagerFactory", transactionManagerRef = "hotelTransactionManager", basePackages = {
"rc.repository" }) //Mirar si se puede sustituir por rc.domain o rc.repository
public class HotelDbConfig {
#Autowired
private Environment env;
#Bean(name = "hotelDataSource")
#ConfigurationProperties(prefix = "hoteles.datasource")
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("hoteles.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("hoteles.datasource.url"));
dataSource.setUsername(env.getProperty("hoteles.datasource.username"));
dataSource.setPassword(env.getProperty("hoteles.datasource.password"));
return dataSource;
}
#Bean(name = "hotelEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("hotelDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("rc.domain")
.persistenceUnit("hotel").build();
}
#Bean(name = "hotelTransactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("hotelEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
database2:
package rc.persistence2;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "cocheEntityManagerFactory", transactionManagerRef = "cocheTransactionManager", basePackages = {
"rc.repository2" })
public class CocheDbConfig {
#Autowired
private Environment env;
#Primary
#Bean(name = "cocheDataSource")
#ConfigurationProperties(prefix = "coches.datasource")
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("coches.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("coches.datasource.url"));
dataSource.setUsername(env.getProperty("coches.datasource.username"));
dataSource.setPassword(env.getProperty("coches.datasource.password"));
return dataSource;
}
#Primary
#Bean(name = "cocheEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("cocheDataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("rc.domain2")
.persistenceUnit("coche").build();
}
#Primary
#Bean(name = "cocheTransactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("cocheEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
But when I try to use repositories from web module:
package rc.web;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import rc.domain2.Coche;
import rc.persistence2.CocheRepository;
#RestController
public class CocheController {
#Autowired
private CocheRepository cocheRepository;
public CocheController(CocheRepository cocheRepository) {
this.cocheRepository = cocheRepository;
}
#GetMapping(value = "/coches")
public List<Coche> getCoches() {
List<Coche> hotels = this.cocheRepository.findAll();
return hotels;
}
}
It shows me the following error:
I've tried differents possibilities but always the same result:
2018-09-27 17:08:58.399 WARN 15272 --- [ main]
ConfigServletWebServerApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'cocheController' defined in file
[C:\springboot-multiple-maven-modules\web\target\classes\rc\web\CocheController.class]:
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'rc.persistence2.CocheRepository' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {} 2018-09-27 17:08:58.399 INFO 15272 --- [
main] j.LocalContainerEntityManagerFactoryBean : Closing JPA
EntityManagerFactory for persistence unit 'coche' 2018-09-27
17:08:58.400 INFO 15272 --- [ main]
j.LocalContainerEntityManagerFactoryBean : Closing JPA
EntityManagerFactory for persistence unit 'hotel' 2018-09-27
17:08:58.403 INFO 15272 --- [ main]
o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-09-27 17:08:58.421 INFO 15272 --- [ main]
ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report
re-run your application with 'debug' enabled. 2018-09-27 17:08:58.670
ERROR 15272 --- [ main]
o.s.b.d.LoggingFailureAnalysisReporter :
*************************** APPLICATION FAILED TO START
Description:
Parameter 0 of constructor in rc.web.CocheController required a bean
of type 'rc.persistence2.CocheRepository' that could not be found.
Action:
Consider defining a bean of type 'rc.persistence2.CocheRepository' in
your configuration.
Please help!!
Thanks in advance!
You got a error in the datasource configuration. Your CocheDbConfig datasource is scanning in the based packages "rc.repository2" to find out Repository class so it can't find the bean 'rc.persistence2.CocheRepository' in your controller.
You should change the based packages in your database2 datasource like this
#EnableJpaRepositories(entityManagerFactoryRef = "cocheEntityManagerFactory", transactionManagerRef = "cocheTransactionManager", basePackages = {
"rc.persistence2" })

How to start HSQLDB in server mode from Spring boot application

I have a Spring boot application, running with jpa data and hsqldb 2.3.3 (in Centos 7), the application runs fine but I would like to use HSQLDB database manager to check the data status, however it failed:
application.properties:
spring.datasource.url=jdbc:hsqldb:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.HSQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
Command to start HSQLDB:
java -cp /home/mycentos/.m2/repository/org/hsqldb/hsqldb/2.3.3/hsqldb-2.3.3.jar org.hsqldb.util.DatabaseManagerSwing
If I tried to log in with HSQLDB server mode, it pops Connection refused error
jdbc:hsqldb:hsql://localhost/testdb
If I tried to log in in-memory db, I can log in but no table and data showing up
jdbc:hsqldb:hsql:testdb
Question:
How to make it works?
Do I have to refer to the hsqldb.jar from tomcat deployment folder because that is the one using by the application?
Any configuration difference to configure hsqldb in server mode or in-memory mode from Spring application?
Can any method make in-memory mode working in such situation (to check data by db created Spring boot)?
To access the HSQL DB created by Spring boot app, you have to start HSQL server. For example, create a XML configuration file hsql_cfg.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.xsd">
<bean id="hqlServer" class="org.hsqldb.server.Server" init-method="start" destroy-method="stop">
<property name="properties"><bean class="org.hsqldb.persist.HsqlProperties">
<constructor-arg><props>
<prop key="server.database.0">mem:testdb</prop>
<prop key="server.dbname.0">testdb</prop><!--DB name for network connection-->
<prop key="server.no_system_exit">true</prop>
<prop key="server.port">9001</prop><!--default port is 9001 -->
</props></constructor-arg>
</bean></property>
</bean>
</beans>
Here is a example to import the XML configuration in main application class.
#SpringBootApplication
#ImportResource(value="classpath:/package/hsql_cfg.xml")
public class MyApplication {
}
The HSQL server will start with Spring boot app. Other applications could connect to the HSQL server using JDBC url
jdbc:hsqldb:hsql://ip_address:port/testdb
Of course, hsqldb.jar is required for loading JDBC driver class.
Just to add to beckyang's answer, here is my approach.
Includes a hack to redirect logs to slf4j.
Includes specifying a corresponding datasource.
import org.hsqldb.jdbc.JDBCDataSource;
import org.hsqldb.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
#Configuration
public class DataSourceConfiguration {
private final Logger log = LoggerFactory.getLogger(getClass());
#Bean(initMethod = "start", destroyMethod = "stop")
#ConfigurationProperties//(prefix = "alarms.idempotent.server")
public Server idempotentServer(#Value("${alarms.idempotent.server.path}") String path, #Value("${alarms.idempotent.port}") int port, #Value("${alarms.idempotent.name}") String name) {
Server server = new Server();
server.setDatabaseName(0, name);
server.setDatabasePath(0, path);
server.setPort(port);
server.setLogWriter(slf4jPrintWriter());
server.setErrWriter(slf4jPrintWriter());
return server;
}
#Bean("idempotentDataSource")
#Primary
#ConfigurationProperties
public DataSource idempotentDataSource(#Value("${alarms.idempotent.datasource.url}") String urlNoPath, #Value("${alarms.idempotent.name}") String name) {
JDBCDataSource jdbcDataSource = new JDBCDataSource();
String url = urlNoPath;
if (!url.endsWith("/")) {
url += "/";
}
url += name;
jdbcDataSource.setUrl(url);
jdbcDataSource.setUser("sa");
return jdbcDataSource;
}
private PrintWriter slf4jPrintWriter() {
PrintWriter printWriter = new PrintWriter(new ByteArrayOutputStream()) {
#Override
public void println(final String x) {
log.debug(x);
}
};
return printWriter;
}
}

org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.MySQLDialect in spring MVC

i am using Spring’s WebApplicationInitializer interface to create the application context programmatically and using hibernate with jpa specification for data persistence. i put db.properties file in src folder adding #PropertySource("classpath:db.properties") in WebAppConfig class. i have following jars for hibernate in classpath.............
antlr-2.7.7.jar aopalliance-1.0.jar
commons-dbcp-1.4-javadoc.jar
commons-dbcp-1.4-sources.jar
commons-dbcp-1.4.jar
commons-logging-1.1.1.jar
commons-pool-1.6-javadoc.jar
commons-pool-1.6-sources.jar
commons-pool-1.6.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.1.9.Final.jar
hibernate-entitymanager-4.1.9.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist-3.17.1-GA.jar
jboss-logging-3.1.0.GA.jar
jta-1.1.jar
mysql-connector-java-5.1.6-bin.jar
web initialzer class code
package com.genesis.init;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class Initializer implements WebApplicationInitializer {
// gets invoked automatically when application starts up
public void onStartup(ServletContext servletContext)
throws ServletException {
// Create ApplicationContext. I'm using the
// AnnotationConfigWebApplicationContext to avoid using beans xml files.
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebAppConfig.class);
// Add the servlet mapping manually and make it initialize automatically
Dynamic servlet = servletContext.addServlet("dispatcher",
new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
WebAppConfig code
package com.genesis.init;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
// specifies this class as configuration
#ComponentScan("com.genesis")
// specifies which package to scan
#EnableWebMvc
// enable spring web mvc to use annotation
#PropertySource("classpath:db.properties")
// plugs in property file which located in the resource folder.
#EnableTransactionManagement
// enables Spring’s annotation-driven transaction management capability.
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment env;
// Tell SpingMVC where to find view scripts
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
// Enable serving static resources even when DispatcherServlet is mapped to
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
// Enable accessing entityManager from view scripts. Required when using
// lazy loading
#Override
public void addInterceptors(InterceptorRegistry registry) {
OpenEntityManagerInViewInterceptor viewInterceptor = new OpenEntityManagerInViewInterceptor();
viewInterceptor.setEntityManagerFactory(entityManagerFactory().getObject());
registry.addWebRequestInterceptor(viewInterceptor);
}
//Set up dataSource to be used by Hibernate. Also make sure the connection doesn't go down
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setUrl(env.getProperty("url"));
dataSource.setDriverClassName(env.getProperty("driver"));
dataSource.setUsername(env.getProperty("user"));
dataSource.setPassword(env.getProperty("pass"));
dataSource.setValidationQueryTimeout(5);
return dataSource;
}
//Set up JPA and transactionManager
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(getDataSource());
emf.setPackagesToScan("com.genesis.model");
// let Hibernate know which database we're using.
// note that this is vendor specific, not JPA
Map<String, Object> opts = emf.getJpaPropertyMap();
opts.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(va);
return emf;
}
//Let us use PlatformTransactionManager directly to implement programmatic approach to implement transactions
//To start a new transaction you need to have a instance of TransactionDefinition
#Bean
public PlatformTransactionManager transactionManager(){
JpaTransactionManager transactionManager=new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager();
}
}
database property file is as.
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
hibernate.dialect=org.hibernate.dialect.MySQLDialect
user=root
pass=iems1234
show_sql=true
packages.to.scan=com.genesis.model
console output is...........
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class com.genesis.init.WebAppConfig: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1507)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1145)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:922)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:493)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:512)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:466)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1267)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1084)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5314)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3920)
at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:426)
at org.apache.catalina.core.ContainerBase.backgroundProcess(ContainerBase.java:1345)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1530)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1540)
at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1519)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build EntityManagerFactory
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:293)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:317)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1566)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1503)
... 27 more
Caused by: org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.MySQLDialect
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:76)
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:64)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:170)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:77)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2283)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2279)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1748)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
... 33 more
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Unable to load class [org.hibernate.dialect.MySQLDialect ]
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:141)
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.constructDialect(DialectFactoryImpl.java:73)
... 44 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : org.hibernate.dialect.MySQLDialect
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl$1.findClass(ClassLoaderServiceImpl.java:99)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:266)
at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:138)
... 45 more
You aren't using Maven or Gradle as a build tool, so you will have to make sure that all of your needed jar files are in the WEB-INF/lib directory of your web application. If it isn't in that directory it isn't on the classpath.
I strongly suggest using one of the earlier mentioned build tools to build your artifact and manage your dependencies. It will save you a lot of searching and headaches.
Links
Maven
Gradle

Resources