I have some problem when inherit session factory and configuration from another project :
I have two separate project (core-project, the projects uses core as library)
configuration of my core-project is the following code :
package ir.badnava.pressmining.core.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
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.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import ir.badnava.pressmining.core.models.raw.base.BaseRawEntity;
import ir.badnava.pressmining.core.models.raw.page.RawPageEntity;
#Configuration
#ComponentScan(basePackages = { "ir.badnava.pressmining" })
#EnableTransactionManagement
#PropertySource(value = { "classpath:database.properties" })
public class AppConfig {
#Autowired
private Environment environment;
#Bean(name = "sessionFactory")
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(getDataSource());
setAnotatedClasses(sessionFactory);
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
protected void setAnotatedClasses(LocalSessionFactoryBean sessionFactory) {
sessionFactory.setAnnotatedClasses(new Class<?>[]{BaseRawEntity.class, RawPageEntity.class});
}
#Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
private Properties getHibernateProperties() {
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"));
return properties;
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager(s);
return txManager;
}
}
and the child project configuration is the following code :
package com.badnava.pressmining.web.crawler.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import com.badnava.pressmining.web.crawler.crawler.WebCrawler;
import com.badnava.pressmining.web.crawler.models.speciallist.RepositoryList;
import com.badnava.pressmining.web.crawler.models.speciallist.RepositoryListManager;
import com.badnava.pressmining.web.crawler.models.urlrepo.UrlRepository;
import com.badnava.pressmining.web.crawler.models.urlrepo.UrlRepositoryManager;
#Configuration
public class AppConfig extends ir.badnava.pressmining.core.config.AppConfig{
#Bean
public RepositoryListManager getRepositoryListManager() {
return new RepositoryListManager();
}
#Bean
public UrlRepositoryManager getUrlRepositoryManager() {
return new UrlRepositoryManager();
}
#Bean
public WebCrawler getWebCrawler(){
return new WebCrawler();
}
#Override
protected void setAnotatedClasses(LocalSessionFactoryBean sessionFactory) {
super.setAnotatedClasses(sessionFactory);
sessionFactory.setAnnotatedClasses(new Class<?>[]{RepositoryList.class, UrlRepository.class});
}
}
and my problem is that in the child project I overload the setAnnotatedClass method and calling it's super and give the session factory my entities class but after doing something like save or update session factory says that unknown mapping entity
I have no idea about what did I wrong in these code because I did that before with XML file configuration
Update :
log :
Exception in thread "Thread-3" org.hibernate.MappingException: Unknown entity: ir.badnava.pressmining.core.models.raw.page.RawPageEntity
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at ir.badnava.pressmining.core.models.raw.base.BaseDao.save(BaseDao.java:16)
at ir.badnava.pressmining.core.models.raw.base.BaseDao$$FastClassBySpringCGLIB$$d95ff2ca.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:280)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at ir.badnava.pressmining.core.models.raw.base.BaseDao$$EnhancerBySpringCGLIB$$95dae3fd.save(<generated>)
at ir.badnava.pressmining.core.models.raw.base.BaseManager.save(BaseManager.java:23)
at com.badnava.pressmining.web.crawler.crawler.WebCrawler$3.run(WebCrawler.java:142)
at java.lang.Thread.run(Thread.java:745)
Problem solved :
the problem was that the setAnnotatedClasses method is a setter method and I changed my code to bellow code and that's work
#Override
protected Class<?>[] setAnotatedClasses() {
Class<?>[] superClasses = super.setAnotatedClasses(sessionFactory);
Class<?>[] childClasses = new Class<?>[]{RepositoryList.class, UrlRepository.class};
Class<?>[] allClasses = new Class<?>[childClasses.length + superClasses.length];
for (int i = 0; i < allClasses.length; i++) {
if (i < superClasses.length)
allClasses[i] = superClasses[i];
else
allClasses[i] = childClasses[i-childClasses.length];
}
return allClasses;
}
thanks to #sura2k
Related
I have this issue. along 3 days.
When I tried to build the app with maven, i have this isues, but my build was successful, then when I deployed on WebLogic and I call any endpoint this response to me a 500 internal server error.
2021-10-29 17:23:47.788 INFO 64993 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.32.Final
2021-10-29 17:23:48.021 INFO 64993 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-10-29 17:23:48.269 WARN 64993 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata
java.sql.SQLException: No suitable driver found for jdbc/facturador
at java.sql.DriverManager.getConnection(DriverManager.java:689) ~[na:1.8.0_202]
at java.sql.DriverManager.getConnection(DriverManager.java:208) ~[na:1.8.0_202]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:155) ~[spring-jdbc-5.3.10.jar:5.3.10]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:146) ~[spring-jdbc-5.3.10.jar:5.3.10]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205) ~[spring-jdbc-5.3.10.jar:5.3.10]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169) ~[spring-jdbc-5.3.10.jar:5.3.10]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) [hibernate-core-5.4.32.Final.jar:5.4.32.Final] (....)
and
2021-10-29 17:23:48.479 INFO 64993 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2021-10-29 17:23:48.501 INFO 64993 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-10-29 17:23:48.507 WARN 64993 --- [ main] o.h.e.j.e.i.JdbcEnvironmentInitiator : HHH000342: Could not obtain connection to query metadata
java.sql.SQLException: No suitable driver found for jdbc/differenceload
at java.sql.DriverManager.getConnection(DriverManager.java:689) ~[na:1.8.0_202]
at java.sql.DriverManager.getConnection(DriverManager.java:208) ~[na:1.8.0_202]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:155) ~[spring-jdbc-5.3.10.jar:5.3.10]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:146) ~[spring-jdbc-5.3.10.jar:5.3.10]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205) ~[spring-jdbc-5.3.10.jar:5.3.10]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169) ~[spring-jdbc-5.3.10.jar:5.3.10]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) [hibernate-core-5.4.32.Final.jar:5.4.32.Final]
There is my DataSourceConfig
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
#Configuration
public class DataSourceConfig {
#Bean(name = "primaryDataSource",destroyMethod = "")
#Primary
#ConfigurationProperties("spring.datasource.primary")
public DataSource firstDataSource(){
return DataSourceBuilder.create().build();
}
#Bean(name = "secondaryDataSource",destroyMethod = "")
#ConfigurationProperties("spring.datasource.secondary")
public DataSource secondDataSource(){
return DataSourceBuilder.create().build();
}
}
Persistence for one DB
import java.util.HashMap;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
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.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
#Configuration
#PropertySource("classpath:/application.properties")
#EnableJpaRepositories(basePackages = "com.gt.tigo.diferenceLoad.entities.facturador", entityManagerFactoryRef = "localEntityManager", transactionManagerRef = "localTransactionManager")
public class PersistenceLocalConfig {
#Autowired
private Environment env;
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean localEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(localDataSource());
em.setPackagesToScan(new String[] { "com.gt.tigo.diferenceLoad.entities.local" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
#Primary
#Bean
public DataSource localDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(env.getProperty("spring.datasource.primary.jndi-name"));
return dataSource;
}
#Primary
#Bean
public PlatformTransactionManager localTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(localEntityManager().getObject());
return transactionManager;
}
}
Persistence for other DB
import java.util.HashMap;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
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.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
#Configuration
#PropertySource("classpath:/application.properties")
#EnableJpaRepositories(basePackages = "com.gt.tigo.diferenceLoad.entities.facturador", entityManagerFactoryRef = "FacturadorEntityManager", transactionManagerRef = "facturadorTransactionManager")
public class PersistenceFacturadorConfig {
#Autowired
private Environment env;
#Bean
public LocalContainerEntityManagerFactoryBean FacturadorEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(facturadorDataSource());
em.setPackagesToScan(new String[] { "com.gt.tigo.diferenceLoad.entities.facturador" });
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
#Bean
public DataSource facturadorDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(env.getProperty("spring.datasource.secondary.jndi-name"));
return dataSource;
}
#Bean
public PlatformTransactionManager facturadorTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(FacturadorEntityManager().getObject());
return transactionManager;
}
}
Here it's my weblogic JNDI.
webLogic jndi
I tried all things.. but can't solve. please I need some help. Thanks!
#Base de datos LOCAL
spring.datasource.primary.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.primary.jndi-name=jdbc/differenceload
#Base de datos FACTURADOR
spring.datasource.secondary.jndi-name=jdbc/facturador
spring.datasource.secondary.driver-class-name=oracle.jdbc.OracleDriver
Quick look and make some changes in your file.
application.properties
spring.datasource.primary.jndi-name=java:/comp/env/jdbc/SecurityDS
spring.datasource.primary.driver-class-name=org.postgresql.Driver
spring.datasource.secondary.jndi-name=java:/comp/env/jdbc/TmsDS
spring.datasource.secondary.driver-class-name=org.postgresql.Driver
Configuration:
#Configuration
#EnableConfigurationProperties
public class AppConfig {
#Bean #ConfigurationProperties(prefix = "spring.datasource.primary")
public JndiPropertyHolder primary() {
return new JndiPropertyHolder();
}
#Bean #Primary
public DataSource primaryDataSource() {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
DataSource dataSource = dataSourceLookup.getDataSource(primary().getJndiName());
return dataSource;
}
#Bean# ConfigurationProperties(prefix = "spring.datasource.secondary")
public JndiPropertyHolder secondary() {
return new JndiPropertyHolder();
}
#Bean
public DataSource secondaryDataSource() {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
DataSource dataSource = dataSourceLookup.getDataSource(secondary().getJndiName());
return dataSource;
}
private static class JndiPropertyHolder {
private String jndiName;
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
}
}
You need to lookup your datasources from jndi instead of creating them using DataSourceBuilder. You can do it like this...
#Configuration
public class WeblogicResourceConfig {
private static final Logger log = LoggerFactory.getLogger(WeblogicResourceConfig.class);
#Autowired
private Environment env;
#Bean
public JndiTemplate jndiTemplate() {
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
return new JndiTemplate(props);
}
// destroyMethod MUST be blank or datasource is removed from jndi tree on
// see https://github.com/spring-projects/spring-framework/issues/17153
#Bean(destroyMethod = "")
#Primary
public DataSource primaryDataSource() throws NamingException {
return (DataSource) jndiTemplate().lookup(env.getProperty("spring.datasource.primary.jndi-name"));
}
// destroyMethod MUST be blank or datasource is removed from jndi tree
// see https://github.com/spring-projects/spring-framework/issues/17153
#Bean(destroyMethod = "")
public DataSource secondaryDataSource() throws NamingException {
return (DataSource) jndiTemplate().lookup(env.getProperty("spring.datasource.secondary.jndi"));
}
}
When creating your LocalContainerEntityManagerFactoryBean inject those datasources above instead of creating new DataSource beans.
I'm working on a new app (to me) and I received the no bean 'entityManagerFactory' available error on startup. Other people who've had this suggest it would not occur had I properly defined the data source. What confuses me is that either Spring Boot/JPA or Flyway (which I'm also using) insists on specific property names being used for your one data source. I'm not sure how someone would handle it if you had more than one. I need to change our application.properties file to fetch from environment variables so they can fetch the values from a secret. I have one definition so that flyway can do it's possible migrations. I have another so that Spring-Boot can do it's JPA based work. I have another because the existing code previously defined a dataSource and gets wired in accordingly. All are going to the same database. I wish I could use only one collection of application.properties properties, but more importantly, I want this entityManagerFactory error resolved. Because my fixes feel like a kludge, I wanted to reach out and see what I'm not understanding.
Here's the application.properties
spring.profiles.active=sprint-vault-services-not-available
spring.application.name=file-generator
file.generator.schema=FILE_GENERATOR
spring.flyway.enabled=true
spring.flyway.locations=classpath:db/migration
spring.flyway.schemas=${file.generator.schema}
spring.flyway.baseline-on-migrate=false
file-generator.date-format=MMddyy
file-generator.time-format=HHmmss
file-generator.ebcdic-output-path=app/output/ebcdic
file-generator.csv-output-path=app/output/csv
file-generator.header-timestamp-format=yyyyMMddHHmmss
file-generator.file-sequence-number=1
logging.path=app/logs
bcupload_datasource_url=${BCUPLOAD_DATASOURCE_URL}
#spring.jpa.properties.hibernate.default_schema=FILE_GENERATOR
bcupload_datasource_username=${BCUPLOAD_DATASOURCE_USERNAME}
bcupload_datasource_password=${BCUPLOAD_DATASOURCE_PASSWORD}
bcupload_datasource_driver=${BCUPLOAD_DATASOURCE_DRIVER}
bcupload_datasource_flyway_db_name=LocalFileGenerator
spring.datasource.driver-class-name=${BCUPLOAD_DATASOURCE_DRIVER}
spring.datasource.url=${BCUPLOAD_DATASOURCE_URL}
spring.datasource.password=${BCUPLOAD_DATASOURCE_PASSWORD}
spring.datasource.username=${BCUPLOAD_DATASOURCE_USERNAME}
spring.jpa.database-platform=DB2Platform
spring.jpa.show-sql=true
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=none
spring.flyway.url= ${BCUPLOAD_DATASOURCE_URL}
spring.flyway.user=${BCUPLOAD_DATASOURCE_USERNAME}
spring.flyway.password=${BCUPLOAD_DATASOURCE_PASSWORD}
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
2021-04-12 23:06:34 DEBUG o.s.b.d.LoggingFailureAnalysisReporter - Application failed to start due to an exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:814)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1282)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:297)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:113)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:691)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:508)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:374)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:134)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1699)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1444)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:623)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:611)
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51)
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:897)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at com.mycompany.cloud.cost.ssc.file.generator.FileGeneratorApplication.main(FileGeneratorApplication.java:22)
Bean definition of datasource:
package com.ibm.cio.cloud.cost.ssc.file.generator.configuration;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.orm.jpa.vendor.HibernateJpaVendorAdapter;
#Configuration
public class DataSourceConfig {
private String dataSourceUrl;
private String userName;
private String password;
private String driver;
/*
#Bean
public EntityManagerFactoryBuilder builder(Environment environment) {
Map<String, String> jpaProperties = new HashMap<>();
jpaProperties.put("hibernate.show_sql", environment.getProperty("spring.jpa.show-sql"));
jpaProperties.put("hibernate.format_sql", environment.getProperty("spring.jpa.properties.hibernate.format_sql"));
jpaProperties.put("hibernate.dialect", environment.getProperty("spring.jpa.properties.hibernate.dialect"));
return new EntityManagerFactoryBuilder(new HibernateJpaVendorAdapter(), jpaProperties, null);
}
*/
#Autowired
public DataSourceConfig(#Value("${bcupload_datasource_url}") String bcupload_datasource_url,
#Value("${bcupload_datasource_username}") String bcupload_datasource_username,
#Value("${bcupload_datasource_password}") String bcupload_datasource_password,
#Value("${bcupload_datasource_driver}") String bcupload_datasource_driver) {
this.dataSourceUrl = bcupload_datasource_url;
this.userName = bcupload_datasource_username;
this.password = bcupload_datasource_password;
this.driver = bcupload_datasource_driver;
}
#Bean(name = "bcUploadDataSource")
public DataSource dataSource() {
return DataSourceBuilder.create()
.url(dataSourceUrl)
.username(userName)
.password(password)
.driverClassName(driver).build();
}
}
I have a project with several datasources and each datasource end up looking something like this:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
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.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
#Configuration
#EnableJpaRepositories(
basePackages = {"com.your.repositories.packages"},
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager")
public class DataSourceConfig{
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.entity.pacakges"});
em.setPersistenceUnitName("your_name");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
properties.put("hibernate.dialect", env.getProperty("spring.jpa.properties.hibernate.dialect"));
properties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql"));
properties.put("hibernate.temp.use_jdbc_metadata_defaults",
env.getProperty("spring.jpa.use_jdbc_metadata_defaults." + NAME));
properties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
properties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
em.setJpaPropertyMap(properties);
return em;
}
#Bean(name = "dataSource")
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
#Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManager().getObject());
return transactionManager;
}
}
So for your error, probably try to use LocalContainerEntityManagerFactoryBean instead of EntityManagerFactoryBuilder
I am new to spring and hibernate as well as to stackoverflow
A developing ecommerce project using spring hibernate maven
creating two file one for frontend and 2nd for backend after creating two file i am adding dependency of backend into frontend pom.ml file
I am using java to create sessionfactory ,datasource and transaction manager
here is the code I dont understand what mistake i am doing
package com.ecom.Config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
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.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;
import
org.springframework.transaction.annotation.EnableTransactionManagement;
import com.ecom.Model.CustomerRegistration;
#Configuration
#ComponentScan("com.ecom")
#EnableTransactionManagement
public class AnnotationConfigApplicationContext {
#Bean(name = "dataSource")
public DataSource getH2DataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl("jdbc:h2:tcp://localhost/~/Ecommerce");
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUsername("sa");
dataSource.setPassword("");
return dataSource;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "create");
return properties;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new
LocalSessionFactoryBuilder(dataSource);
sessionBuilder.addProperties(getHibernateProperties());
sessionBuilder.addAnnotatedClass(CustomerRegistration.class);
return sessionBuilder.buildSessionFactory();
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory
sessionFactory) {
HibernateTransactionManager transactionManager = new
HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
Contoller
package com.ecom.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ecom.DAO.CustomerRegDAO;
import com.ecom.Model.CustomerRegistration;
#Controller
public class CustomerRegController
{
#Autowired
private CustomerRegDAO customerRegDAO ;
#RequestMapping("/registrationForm")
public String Registration(Model theModel)
{
CustomerRegistration theCustomerRegistration = new
CustomerRegistration();
theModel.addAttribute("customer", theCustomerRegistration);
return "registration-form";
}
#RequestMapping("/saveCustomer")
public String saveCustomer(#ModelAttribute("customer")
CustomerRegistration theCustomerRegistration)
{
customerRegDAO.saveCustomer(theCustomerRegistration);
return "index";
}
}
DAO
package com.ecom.DAOImplementation;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import com.ecom.DAO.CustomerRegDAO;
import com.ecom.Model.CustomerRegistration;
#Repository("CustomerRegDAO")
#Transactional
public class CustomerRegDAOImpl implements CustomerRegDAO {
private SessionFactory sessionFactory;
#Transactional
public void saveCustomer(CustomerRegistration theCustomerRegistration) {
Session currentsession = sessionFactory.getCurrentSession();
currentsession.saveOrUpdate(theCustomerRegistration);
}
}
Error:
Type Exception Report
Message Servlet.init() for servlet [spring] threw exception
Description The server encountered an unexpected condition that prevented
it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet.init() for servlet [spring] threw
exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase
.java:475)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogVa
lve.java:651)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:498)
Root cause
org.springframework.beans.factory.BeanCreationException: Error creating
bean
with name 'sessionFactory' defined in
com.ecom.Config.AnnotationConfigApplicationContext: 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.NoClassDefFoundError: Could not
initialize class
org.hibernate.annotations.common.reflection.java.JavaReflectionManager
java.lang.NoClassDefFoundError: Could not initialize class
org.hibernate.annotations.common.reflection.java.JavaReflectionManager
The exception is indicating that the class JavaReflectionManager is not found. This class is present in hibernate-commons-annotations jar file. Can you add this in your pom.xml and try running it again?
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.2.Final</version>
</dependency>
I have created ear project with one web module and one EJB module.
I'm using web module for Spring MVC view and controller. Model, service and repository are maintained in ejb module. (tried in JAR module as well).
I'm getting exception like, [springframework.web.servlet.DispatcherServlet] (ServerService Thread Pool -- 168) Context initialization failed: java.lang.IllegalStateException: Cannot load configuration class: com.sakthi.core.config.HibernateConfiguration Exception.
My HibernateConfiguration class is,
package com.sakthi.core.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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
public class HibernateConfiguration {
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.sakthi.core.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
My Complete project is copied in github URL: https://github.com/newway86/Spring4MVCHibernateEAR/tree/master/myapp
Please help me... I'm trying for 2 months. Not yet getting the sollution.
This actual program has been taken from this URL: http://websystique.com/springmvc/spring-4-mvc-and-hibernate4-integration-example-using-annotations/
If I try the above example in web project, its working fine. But not working while I create it as a ear project and moved the core logics to the ejb module.
Hey everyone am using spring MVC And I want ot integrate JPA Repository with JNDI Data Source , i have an app without jpa repository here's my code :
mvcConfiguration class to create my Datasource :
package net.codejava.spring.config;
import javax.naming.NamingException;
import javax.sql.DataSource;
import net.codejava.spring.dao.UserDAO;
import net.codejava.spring.dao.UserDAOImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jndi.JndiTemplate;
import org.springframework.web.servlet.ViewResolver;
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;
#Configuration
#ComponentScan(basePackages="net.codejava.spring")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public UserDAO getUserDao() throws NamingException {
JndiTemplate jndiTemplate = new JndiTemplate();
DataSource dataSource = (DataSource) jndiTemplate.lookup("java:comp/env/jdbc/postgres2");
return new UserDAOImpl(dataSource);
}
}
this Dao layer that i want to replace with Jpa repository
package net.codejava.spring.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import net.codejava.spring.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class UserDAOImpl implements UserDAO {
private DataSource dataSource;
public UserDAOImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<User> list() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "SELECT * from users";
List<User> listUser = jdbcTemplate.query(sql, new RowMapper<User>() {
#Override
public User mapRow(ResultSet rs, int rowNumber) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setEmail(rs.getString("email"));
return user;
}
});
return listUser;
}
}
and the context.xml
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/postgres2" auth="Container"
type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://127.0.0.1:5432/mydb"
username="postgres" password="root" maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>
Thanks for any guide ..