Multiple DB configuration in java spring throws exception - java

I am using two different databases for my spring hibernate application.
I defined two persistence config file for creating two session factory.
When i start the servlet container it throws below exception
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'transactionManager' defined in class path resource
PersistenceConfig1
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:persistence.properties" })
#ComponentScan({ "com.test.test2.*" })
public class PersistenceConfiguration1 {
#Autowired
private Environment env;
#Bean(name="fSessionFactory")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(testDataSource());
sessionFactory.setPackagesToScan(new String[] {
" com.test.test2"});
sessionFactory.setHibernateProperties(hibernateProperties1());
return sessionFactory;
}
#Bean
public DataSource testDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties hibernateProperties1() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect",
env.getProperty("hibernate.dialect"));
setProperty("hibernate.globally_quoted_identifiers", "true");
}
};
}
}
Persistence Config 2
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:persistence.properties" })
#ComponentScan({ "com.test.test3.*" })
public class PersistenceConfigurationDOTC {
#Autowired
private Environment env;
#Bean(name="dSessionFactory")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(test1DataSource());
sessionFactory.setPackagesToScan(new String[] {
"com.test.test3.entity"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource test1DataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc1.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc1.url"));
dataSource.setUsername(env.getProperty("jdbc1.user"));
dataSource.setPassword(env.getProperty("jdbc1.pass"));
return dataSource;
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect",
env.getProperty("hibernate.dialect"));
setProperty("hibernate.globally_quoted_identifiers", "true");
}
};
}
}
If I defined two transaction manager also im getting exception.
Help me on how to configure two transaction managers in one spring hibernate application.

Do you want a single transaction manager for both the configs? Or would you prefer a multiple config? Try defining transaction manager in your Persistence Config 2 too.

Related

Hibernate Spring: spring.jpa.hibernate.ddl-auto property doesn't create generate tables doesn't work

I'm using Spring MVC with Hibernate. I configure Hibernate using configuration Java class:
DbConfig.java:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "testproject", entityManagerFactoryRef = "entityManagerFactory")
public class DbConfig {
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(getDatasource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setJpaProperties(getHibernateProperties());
entityManagerFactoryBean.setPackagesToScan("testproject");
return entityManagerFactoryBean;
}
#Bean
public DataSource getDatasource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://127.0.0.1:5432/testproject");
dataSource.setUsername("postgres");
dataSource.setPassword("mypass");
return dataSource;
}
#Bean
public SessionFactory getSessionFactory() throws IOException {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setPackagesToScan("testproject");
//getHibernateProperties method is a private method
sessionFactoryBean.setHibernateProperties(getHibernateProperties());
sessionFactoryBean.setDataSource(getDatasource());
sessionFactoryBean.afterPropertiesSet();
return sessionFactoryBean.getObject();
}
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager() throws IOException {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory());
return transactionManager;
}
private static Properties getHibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
hibernateProperties.put("hibernate.show_sql", false);
hibernateProperties.put("spring.jpa.hibernate.ddl-auto", "create");
System.out.println();
// other properties
return hibernateProperties;
}
}
The auto-creation of tables is configured inside getHibernateProperties method:
hibernateProperties.put("spring.jpa.hibernate.ddl-auto", "create");
However it doesn't seem to work: after I deploy server and try to insert an entity I get an error and the database has no tables.
The property spring.jpa.hibernate.ddl-auto is of type org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.Hibernate which is from Spring Boot. But you are using Spring MVC.
use hibernate.hbm2ddl.auto instead.
Further Reading
Metadata Format in Spring Boot Reference
This is the properties code that works:
#Bean
private static Properties getHibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
hibernateProperties.put("hibernate.show_sql", true);
hibernateProperties.put( "hibernate.hbm2ddl.auto", "create-drop");
return hibernateProperties;
}

How to configure Datasource using #Bean in Java class

I'm following an example in a Spring book to create a little web store application.
The example uses the hsqldb embedded Database, but I don't want to use it.
I want to connect to a MySQL database and, later, use the Hibernate sessionFractory.
I edited the example code this way:
#Configuration
#ComponentScan("com.packagename.webstore")
public class RootApplicationContextConfig {
#Bean
public DataSource dataSource() {
// this is the original code of the example
/*EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder
.setType(EmbeddedDatabaseType.HSQL)
.addScript("db/sql/create-table.sql")
.addScript("db/sql/insert-data.sql")
.build();
return db; */
//this is my code
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/dbName");
dataSource.setUsername( "user" );
dataSource.setPassword( "pass" );
return dataSource;
}
}
Then, in my classes I access the datasource this way:
#Autowired
private DataSource datasource;
...
Connection connection = datasource.getConnection();
...
Is it correct what I did?
If later I want to use the Hibernate sessionFactory, how should I edit my code?
Thank you guys
If you want configure SessionFactory with spring then to create required beans like below
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:persistence-mysql.properties" })
#ComponentScan({ "org.baeldung.spring.persistence" })
public class PersistenceConfig {
#Autowired
private Environment env;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(
new String[] { "entity class package name so it can scan them" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource restDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager txManager
= new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect",
env.getProperty("hibernate.dialect"));
setProperty("hibernate.globally_quoted_identifiers",
"true");
}
};
}
}
property file
# jdbc confi
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate_dev?createDatabaseIfNotExist=true
jdbc.user=tutorialuser
jdbc.pass=tutorialmy5ql
# hibernate config
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
then you can you and Datasource or SessionFactory in your required class
public class HibernateDAO{
#Autowired
SessionFactory sessionFactory;
#Autowired
DataSource datasource;
}
Here is example link

java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist Spring Data source

I am converting working hibernate project to Spring hibernate Project.In the existing project session factory creation has been done by loading hibernate cfg file.Since im going for spring i modified the session creation via Localsessionfactory by configuring in java.I am getting one strange exception as below
ORA-00942: table or view does not exist
But the same working fine in the hiberate cfg lookup.
I am using two transcation manager .Below is my code
Repository clas
#Repository
public class TestImpl implements
TestRepository {
#Autowired
#Qualifier("fSessionFactory")
SessionFactory sessionFactory;
#Autowired
#Qualifier("dSessionFactory")
SessionFactory sessionFactory2;
#SuppressWarnings("unchecked")
#Transactional("dTransaction")
public Recordse getOrders(String code, int id ) throws PersistenceException {
Session session = null;
try {
session =sessionFactory.getCurrentSession();
List<Order> orderList = session
.createQuery("FROM Orders WHERE CODE = :code AND NUM_CC = :id " )
.setParameter("code", code)
.setParameter("id", id)
.list();
}
catch (Exception e) {
throw new PersistenceException(e);
}
return empSickTime ;
}
#Transactional("fTransaction")
#Override
public SelectedRecords getRecords(String code, String grpId) throws PersistenceException {
Session session = null;
try {
session = sessionFactory2.getCurrentSession();
List<Records> recList = session
.createQuery("FROM Records WHERE CODE = :code AND GRP_CC = :id " )
.setParameter("code", code)
.setParameter("id", id)
.list();
}
}
catch (HibernateException e) {
throw new PersistenceException(e);
}
return qualifiedFleet;
}
}
PersistencConfig1
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:persistence.properties" })
#ComponentScan({ "com.test.test2.*" })
public class PersistenceConfiguration1 {
#Autowired
private Environment env;
#Bean(name=" ")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(testDataSource());
sessionFactory.setPackagesToScan(new String[] {
" com.test.test2"});
sessionFactory.setHibernateProperties(hibernateProperties1());
return sessionFactory;
}
#Bean
public DataSource testDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
#Bean(name="dTransaction")
#Autowired
public HibernateTransactionManager transactionManager(
SessionFactory sessionFactory) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties hibernateProperties1() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect",
env.getProperty("hibernate.dialect"));
setProperty("hibernate.globally_quoted_identifiers", "true");
}
};
}
}
PersistenceConfig2
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:persistence.properties" })
#ComponentScan({ "com.test.test3.*" })
public class PersistenceConfigurationDOTC {
#Autowired
private Environment env;
#Bean(name="dSessionFactory")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(test1DataSource());
sessionFactory.setPackagesToScan(new String[] {
"com.test.test3.entity"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource test1DataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc1.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc1.url"));
dataSource.setUsername(env.getProperty("jdbc1.user"));
dataSource.setPassword(env.getProperty("jdbc1.pass"));
return dataSource;
}
#Bean(name = "fTransaction")
#Autowired
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactoryFCDS().getObject());
return txManager;
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto",
env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect",
env.getProperty("hibernate.dialect"));
setProperty("hibernate.globally_quoted_identifiers", "true");
}
};
}
}
Did I miss anything?
#Bean(name=" ")
public LocalSessionFactoryBean sessionFactory() {
It looks like your bean name is incorrect?
Another thing is in your fTransaction you are using session factory from your dSessionFactory as you declare sessionFactory2
#Autowired
#Qualifier("dSessionFactory")
SessionFactory sessionFactory2;
and then use in fTransaction
#Transactional("fTransaction")
#Override
public SelectedRecords getRecords(String code, String grpId) throws PersistenceException {
Session session = null;
try {
session = sessionFactory2.getCurrentSession();
I guess you are referring to the wrong DB connection.
Next time I would suggest giving your attributes more meaningful names, like paymentSessionFactory, geoSessionFactory & etc so that you won't mix var1 vs session2

Spring 4 Migrate from hibernate 4 to 5 session return null

After upgrading libs version to last and refreshing configurations session start giving null objects.
I tried with different configurations, but this may be better from all.
Could you help and explain what happened with upgrade?
<spring.version>4.2.5.RELEASE</spring.version>
<hibernate.version>5.1.0.Final</hibernate.version>
#Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[]{"com.project"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
}
#Bean
public DataSource restDataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource(env.getProperty("jdbc.url"),
env.getProperty("jdbc.user"), env.getProperty("jdbc.pass"));
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
return dataSource;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
final Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
setProperty("hibernate.current_session_context_class", "org.springframework.orm.hibernate5.SpringSessionContext");
setProperty("hibernate.implicit_naming_strategy","org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl");
setProperty("hibernate.format_sql","false");
setProperty("hibernate.use_sql_comments","false");
setProperty("hibernate.id.new_generator_mappings","true");
setProperty("hibernate.enable_lazy_load_no_trans","true");
setProperty("hibernate.max_fetch_depth","1");
setProperty("hibernate.default_batch_fetch_size","16");
}
};
}
You need to make sure your import of LocalSessionFactoryBean is of hibernate 5
org.springframework.orm.hibernate5.LocalSessionFactoryBean

How Spring #Autowired binds the SessionFactory object even if there is no SessionFactory instance available

I'm using Hibernate and Spring with Java-based configurations. My config file is this one:
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "dto" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
Working fine. No problem with this, but when I manually try to set the sessionfactory parameter for trasactionManager, like this:
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory());
return txManager;
}
The IDE is showing:
`The method setSessionFactory(SessionFactory) in the type HibernateTransactionManager is not applicable for the arguments (LocalSessionFactoryBean)`
So, I created a sessionFactory like below
#Bean
#Autowired
public SessionFactory sessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionFactory = new LocalSessionFactoryBuilder(dataSource);
sessionFactory.addProperties(hibernateProperties());
sessionFactory.scanPackages("dto");
return sessionFactory.buildSessionFactory();
}
and passed to trasactionManager It worked.
My question is how spring autowired the sessionFactory object even if there is no no sessionFactory instance present in the 1st approach?
You need to change the method return types from SessionFactory to HibernateTransactionManager.
This is how it should look like:
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public SessionFactory sessionFactory() {
Properties properties = new Properties();
properties.setProperty("hibernate.show_sql", "true")
properties.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory")
properties.setProperty("hibernate.cache.use_query_cache", "true")
properties.setProperty("hibernate.cache.use_second_level_cache", "true")
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
return new LocalSessionFactoryBuilder(dataSource())
.scanPackages("dto")
.addProperties(properties)
.buildSessionFactory();
}

Categories