ERROR 11664 --- [main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000231: Schema export unsuccessful - spring

I'm trying to get a small project of mine working, regarding the implementation of a process via WebServices.
Problem is: I dont even get to that point because I seem to hit trouble when booting Spring.
Spring is in fact booting but I cant get hibernate working ( atleast I think the problem lies with hibernate? ).
My ErrorLog: onPasteBin
My application.properties:
#New
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.show-sql = true
# Hibernate
spring.jpa.hibernate.ddl-auto=create
#Old
# Thymeleaf
spring.thymeleaf.cache: false
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://127.0.0.1:3306/igt
db.username: root
db.password: passwort
# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: com.entities
And my DatabaseConfig.java:
package com.configs;
import org.springframework.beans.factory.annotation.Value;
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;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableTransactionManagement
public class DatabaseConfig {
#Value("${db.driver}")
private String DB_DRIVER;
#Value("${db.password}")
private String DB_PASSWORD;
#Value("${db.url}")
private String DB_URL;
#Value("${db.username}")
private String DB_USERNAME;
#Value("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${hibernate.show_sql}")
private String HIBERNATE_SHOW_SQL;
#Value("${hibernate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
#Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager =
new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
I dont think the Application.java is really relevant to this, but here it is nonetheless:
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Maybe the Project Structure is helpful:
Screenshot of the ProjectStructure
Thanks very much in advance =)

Related

Spring boot: I need an explanation for a few lines of code

I am studying spring boot, and am failing to understand a few lines of code.
Referring to the code below, I would like to understand what is needed
#ComponentScan ("boot.entry")
and these two lines declared in the transactionManager() method, that is
HibernateTransactionManager txManager = new HibernateTransactionManager ();
txManager.setSessionFactory (sessionFactory (). getObject ());
Can anyone kindly help me?
package config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableTransactionManagement
#EnableAutoConfiguration(exclude = { HibernateJpaAutoConfiguration.class})
#ComponentScans(value = { #ComponentScan("boot.entry"),
#ComponentScan("Model"),
#ComponentScan("Controller"),
#ComponentScan("DAO"),
#ComponentScan("Miscallaneous"),
#ComponentScan("Service")})
public class Config {
#Value("${db.driver}")
private String DB_DRIVER;
#Value("${db.password}")
private String DB_PASSWORD;
#Value("${db.url}")
private String DB_URL;
#Value("${db.username}")
private String DB_USERNAME;
#Value("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${hibernate.show_sql}")
private String HIBERNATE_SHOW_SQL;
#Value("${hibernate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
#Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
sessionFactory.setHibernateProperties(hibernateProperties);
return sessionFactory;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
}
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver resolver= new InternalResourceViewResolver();
resolver.setPrefix("/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
#ComponentScan ("boot.entry")
#ComponentScan basically instruct the Spring IoC to track down the entities for dependency injection.
HibernateTransactionManager txManager = new HibernateTransactionManager ();
txManager.setSessionFactory (sessionFactory (). getObject ());
HibernateTransactionManager handles the transaction handling which requires HibernateSession which is basically an instance of datasource wrapped within JPA specification to handle OOP oriented query handling.
#ComponentScan ("boot.entry") Means that It should load all Components (Beans, Services etc) inside the boot.entry package, which probably should be contained in your project.
Hibernate is an ORM library that lets you do SQL queries without writing SQL. What you are doing in your code is basically initializing the transactionManager with the data from the sessionFactory() function.

NoSuchMethodError Table.indexes() hibernate-core-5.2.13.Final.jar when try to start application?

There is application srping+jpa. Webserver is Websphere 8.5.13
So, I launch application by using WebApplicationInitializer where I add configs.
There is problem when added PersisnteceConfig:
import org.hibernate.jpa.HibernatePersistenceProvider;
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.data.jpa.repository.config.EnableJpaAuditing;
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.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableTransactionManagement
#EnableJpaAuditing
#EnableJpaRepositories(basePackages = {"persistence"})
#PropertySource("classpath:application.properties")
#ComponentScan(basePackages = {"persistence"})
public class PersistenceConfig {
private static final String PROP_DATABASE_DRIVER = "db.driver";
private static final String PROP_DATABASE_URL = "db.url";
private static final String PROP_DATABASE_USERNAME = "db.username";
private static final String PROP_DATABASE_PASSWORD = "db.password";
private static final String PROP_HIBERNATE_DIALECT = "db.hibernate.dialect";
private static final String PROP_HIBERNATE_SHOW_SQL = "db.hibernate.show_sql";
private static final String PACKAGE_WITH_JPA_ENTITIES = "ru.sbrf.risks.services.data.persistence";
private static final String PROP_HIBERNATE_HBM2DDL_AUTO = "db.hibernate.hbm2ddl.auto";
private static final String DO_NOT_AUDIT_LOCKING_FIELD = "org.hibernate.envers.do_not_audit_optimistic_locking_field";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROP_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROP_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROP_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROP_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
System.out.println("1");
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
System.out.println("2");
entityManager.setDataSource(dataSource());
System.out.println("3");
entityManager.setPackagesToScan(PACKAGE_WITH_JPA_ENTITIES);
System.out.println("4");
entityManager.setPersistenceProviderClass(HibernatePersistenceProvider.class);
System.out.println("5");
entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
System.out.println("6");
entityManager.setJpaProperties(getHibernateProperties());
System.out.println("7");
return entityManager;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
//Set properties hibernate
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", env.getRequiredProperty(PROP_HIBERNATE_DIALECT));
properties.put("hibernate.show_sql", env.getRequiredProperty(PROP_HIBERNATE_SHOW_SQL));
properties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty(PROP_HIBERNATE_HBM2DDL_AUTO));
properties.put("org.hibernate.envers.do_not_audit_optimistic_locking_field",
env.getRequiredProperty(DO_NOT_AUDIT_LOCKING_FIELD));
properties.put("verifyServerCertificate", false);
properties.put("useSSL", false);
properties.put("requireSSL", false);
properties.put("useLegacyDatetimeCode", false);
properties.put("useUnicode", "yes");
properties.put("characterEncoding", "UTF-8");
properties.put("serverTimezone", "UTC");
properties.put("useJDBCCompliantTimezoneShift", true);
return properties;
}
}
So,I use hibernate-core-5.2.13.Final libriary and when try to launch application on WebSphere 8.5.13, I have an error message:
Invocation of init method failed; nested exception is
java.lang.NoSuchMethodError:
javax/persistence/Table.indexes()[Ljavax/persistence/Index; (loaded
from
file:/opt/IBM/WebSphere/AppServer/plugins/javax.j2ee.persistence.jar
by org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader#ec08ccb6)
called from class org.hibernate.cfg.annotations.EntityBinder (loaded
from
file:/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/installedApps/MyApp_war.ear/MyApp.war/WEB-INF/lib/hibernate-core-5.2.13.Final.jar
by
com.ibm.ws.classloader.CompoundClassLoader#7f080f2e[war:MyApp_war/MyApp.war]
You're attempting to use a version of Hibernate that implements a different spec version than the JPA 2.0 included in WebSphere 8.5.5. That can be done, but you'll need to bring your own version of the JPA API as well. To do that, you'll either need to switch your web module's class loader to "Parent Last" or move Hibernate and the JPA API jar(s) to a shared library and configure the library to use an isolated class loader (which effectively sets "Parent Last" just for the jars in the library).

Hibernate exception when try to launch Tomcat

I have application on spring-mvc+jpa. I build war and try to start on tomcat.
DataConfig:
import org.hibernate.ejb.HibernatePersistence;
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.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.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableTransactionManagement
#PropertySource("classpath:app.properties")
public class DataConfig {
private static final String PROP_DATABASE_DRIVER = "db.driver";
private static final String PROP_DATABASE_URL = "db.url";
private static final String PROP_DATABASE_USERNAME = "db.username";
private static final String PROP_HIBERNATE_DIALECT = "db.hibernate.dialect";
private static final String PROP_HIBERNATE_SHOW_SQL = "db.hibernate.show_sql";
private static final String PROP_ENTITYMANAGER_PACKAGES_TO_SCAN = "db.entitymanager.packages.to.scan";
private static final String PROP_HIBERNATE_HBM2DDL_AUTO = "db.hibernate.hbm2ddl.auto";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROP_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROP_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROP_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty("db.password"));
return dataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
entityManager.setDataSource(dataSource());
entityManager.setPackagesToScan(env.getRequiredProperty(PROP_ENTITYMANAGER_PACKAGES_TO_SCAN));
entityManager.setPersistenceProviderClass(HibernatePersistence.class);
entityManager.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManager.setJpaProperties(getHibernateProperties());
return entityManager;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put(PROP_HIBERNATE_DIALECT, env.getRequiredProperty(PROP_HIBERNATE_DIALECT));
properties.put(PROP_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROP_HIBERNATE_SHOW_SQL));
properties.put(PROP_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROP_HIBERNATE_HBM2DDL_AUTO));
return properties;
}
}
app.properties is:
#DB properties:
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/mydb
db.username=root
db.password=111111
#Hibernate Configuration:
db.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
db.hibernate.show_sql=true
db.entitymanager.packages.to.scan=ru.sbrf.risks.services.data.model
db.hibernate.hbm2ddl.auto = create-drop
So, there is error message in tomcat logs:
Caused by: javax.persistence.PersistenceException: [PersistenceUnit:
default] Unable to build EntityManagerFactory at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:924)
at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:899)
at
org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:76)
at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:287)
at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549)
... 57 more Caused by: org.hibernate.HibernateException: Connection
cannot be null when 'hibernate.dialect' not set at
org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:97)
at
org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:67)
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.Configuration.buildTypeRegistrations(Configuration.java:1818)
at
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1776)
at
org.hibernate.ejb.EntityManagerFactoryImpl.(EntityManagerFactoryImpl.java:96)
at
org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:914)
... 63 more
Hibernate doesn't understand the properties you are passing it. You have hibernate.dialect defined as db.hibernate.dialect Remove the db portion and just have it as hibernate.dialect and do the same with your other hibernate related properties.
https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/session-configuration.html
#PropertySource("classpath:app.properties")
This annotation value replace with below passing value
#PropertySource(value = {"classpath:application.properties","file:config/application.properties"}, ignoreResourceNotFound = true)
and rebuild you project.now it's working fine.

How to support multiple databases engines on Spring?

I’m building a Spring Boot application that should support various databases engines (MySQL, PostgreSQL, Oracle, SQL Server).
The user will be prompted to select which database it would like to use when installing the application and all tables will be created after this. I think that I should save the user option somewhere and then use it to select the right engine that my application will use to instantiate the repositories.
I googled for some references or best practices that I should follow to implement this but wasn’t able to find (maybe I’m searching the wrong terms - sorry).
Do you have any resource that points me to the right direction?
Thanks a lot!!!
You can refer sample. In sample I use hibernate + spring boot for multiple databases.
You can work by this way:
Step 1: you declare in application.properties info connect of database (mysql, oracle, postgresql)
# MySQL-Database
mysql.db.driver: com.mysql.jdbc.Driver
mysql.db.url: jdbc:mysql://localhost:3306/test
mysql.db.username: root
mysql.db.password: root
mysql.hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
mysql.entitymanager.packagesToScan: com.test.mysql
# postgresql-Database
postgresql.db.driver: org.postgresql.Driver
postgresql.db.url: jdbc:postgresql://localhost:5432/postgres_demo
postgresql.db.username: root
postgresql.db.password:
postgresql.hibernate.dialect: org.hibernate.dialect.PostgreSQLDialect
postgresql.entitymanager.packagesToScan: com.test.postgresql
# Oracle-Database
oracle.db.driver: oracle.jdbc.driver.OracleDriver
oracle.db.url: jdbc:oracle:thin:#localhost:1521:xe
oracle.db.username: root
oracle.db.password:
oracle.hibernate.dialect: org.hibernate.dialect.Oracle10gDialect
oracle.entitymanager.packagesToScan: com.test.oracle
Step 2: In project spring boot you can refer structure project such as:
Step 3 : Implement data source for mysql, oracle, postgresql. you can refer MysqlDatabaseConfig.java, OracleDatabaseConfig.java, PostgresDatabaseConfig.java
package com.test.mysql;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
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 MysqlDatabaseConfig {
#Value("${mysql.db.driver}")
private String DB_DRIVER;
#Value("${mysql.db.password}")
private String DB_PASSWORD;
#Value("${mysql.db.url}")
private String DB_URL;
#Value("${mysql.db.username}")
private String DB_USERNAME;
#Value("${mysql.hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${mysql.entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Bean(name="mysqlDataSource")
#Primary
public DataSource cmrDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean(name="mysqlSessionFactory")
public LocalSessionFactoryBean crmSessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(cmrDataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
#Bean(name="mysqlTransactionManager")
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(crmSessionFactory().getObject());
return transactionManager;
}
}
OracleDatabaseConfig.java
package com.test.oracle;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableTransactionManagement
public class OracleDatabaseConfig {
#Value("${oracle.db.driver}")
private String DB_DRIVER;
#Value("${oracle.db.password}")
private String DB_PASSWORD;
#Value("${oracle.db.url}")
private String DB_URL;
#Value("${oracle.db.username}")
private String DB_USERNAME;
#Value("${oracle.hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${oracle.entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Bean(name="oracleDataSource")
#Primary
public DataSource cmrDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean(name="oracleSessionFactory")
public LocalSessionFactoryBean crmSessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(cmrDataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
#Bean(name="oracleTransactionManager")
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(crmSessionFactory().getObject());
return transactionManager;
}
}
PostgresDatabaseConfig.java
package com.test.postgresql;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
#EnableTransactionManagement
public class PostgresDatabaseConfig {
#Value("${postgresql.db.driver}")
private String DB_DRIVER;
#Value("${postgresql.db.password}")
private String DB_PASSWORD;
#Value("${postgresql.db.url}")
private String DB_URL;
#Value("${postgresql.db.username}")
private String DB_USERNAME;
#Value("${postgresql.hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${postgresql.entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Bean(name="postgresqlDataSource")
#Primary
public DataSource cmrDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean(name="postgresqlSessionFactory")
public LocalSessionFactoryBean crmSessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(cmrDataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
#Bean(name="postgresqlTransactionManager")
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(crmSessionFactory().getObject());
return transactionManager;
}
}
Step 4: call to use:
in case mysql
package com.test.mysql.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional("mysqlTransactionManager")
public class TestMysqlDao {
#Autowired
#Qualifier("mysqlSessionFactory")
private SessionFactory sessionFactory;
}
In case oracle
package com.test.oracle.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional("oracleTransactionManager")
public class TestOracleDao {
#Autowired
#Qualifier("oracleSessionFactory")
private SessionFactory sessionFactory;
}
In case postgresql
package com.test.postgresql.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional("postgresqlTransactionManager")
public class TestPostgresDao {
#Autowired
#Qualifier("postgresqlSessionFactory")
private SessionFactory sessionFactory;
}
It's unclear what you mean by installing but if you want your application to start with different databases you can use different Spring profiles with your application.yml Spring boot profiles
---
spring:
profiles: postgres
datasource:
url:
username:
password:
driver-class-name: org.postgresql.Driver
---
spring:
profiles: mysql
datasource:
url:
username:
password:
driver-class-name: com.mysql.jdbc.Driver
You can then start the application with the respective profile
java -jar -Dspring.profiles.active=mysql yourapp.jar
You can define different connections and get them with specific methods
private DataSource mySqlDataSource;
private DataSource postgresDataSource;
public Connection getMySqlConnection() throws SQLException {
mySqlDataSource.getConnection();
}
public Connection getPostgresConnection() throws SQLException {
postgresDataSource.getConnection();
}

hibernate multiple database configuration files

I have the database config show below file that reads from the application.properties which has information to connect to a single data base.
I want to add another similar configuration file that will allow me to connect to another database and use its session factory like the primary one I already have.
I am working on making another similar file which reads from another application properties file. However I am not sure how to wire it so that I can have multiple session factories in each of my entity classes
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
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 DatabaseConfig {
#Value("${db.driver}")
private String DB_DRIVER;
#Value("${db.password}")
private String DB_PASSWORD;
#Value("${db.url}")
private String DB_URL;
#Value("${db.username}")
private String DB_USERNAME;
#Value("${hibernate.dialect}")
private String HIBERNATE_DIALECT;
#Value("${hibernate.show_sql}")
private String HIBERNATE_SHOW_SQL;
#Value("${hibernate.hbm2ddl.auto}")
private String HIBERNATE_HBM2DDL_AUTO;
#Value("${entitymanager.packagesToScan}")
private String ENTITYMANAGER_PACKAGES_TO_SCAN;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(DB_DRIVER);
dataSource.setUrl(DB_URL);
dataSource.setUsername(DB_USERNAME);
dataSource.setPassword(DB_PASSWORD);
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
Properties hibernateProperties = new Properties();
hibernateProperties.put("hibernate.dialect", HIBERNATE_DIALECT);
hibernateProperties.put("hibernate.show_sql", HIBERNATE_SHOW_SQL);
hibernateProperties.put("hibernate.hbm2ddl.auto", HIBERNATE_HBM2DDL_AUTO);
sessionFactoryBean.setHibernateProperties(hibernateProperties);
return sessionFactoryBean;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager =
new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
} // class DatabaseConfig
Usage of session factory in a generic dao. I would like another session factory that can connect to another datasource.
#Repository("baseDao")
#Transactional
public class BaseDaoImpl<T extends Serializable> implements BaseDao<T> {
#Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.getCurrentSession();
}
...

Resources