Spring configuration for using 2 hibernate sessionFactories - java

I want to use 2 hibernate db connections. I am facing this error, i tries to solved if but could not find a way. I have made two different configuration files and annotated #bean and #qualifires but it still dosent work.
Error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'transactionManager' defined in class path resource [com/project/configuration/RepositoryConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No qualifying bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: sessionFactory2,sessionFactory; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] is defined: expected single matching bean but found 2: sessionFactory2,sessionFactory
My configurations :
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:hibernate.properties" })
public class RepositoryConfig2 {
#Autowired
private Environment environment;
#Bean(name="sessionFactory2")
public LocalSessionFactoryBean sessionFactory2() {
LocalSessionFactoryBean sessionFactory2 = new LocalSessionFactoryBean();
sessionFactory2.setDataSource(dataSource2());
sessionFactory2.setHibernateProperties(hibernateProperties());
sessionFactory2.setPackagesToScan(new String[] { "com.project" });
return sessionFactory2;
}
#Bean
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect2"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql2"));
properties.put("hibernate.hbm2ddl.auto", "update");// environment.getRequiredProperty("hibernate.hbm2ddl.auto")
return properties;
}
#Bean(name = "datasource2")
public DataSource dataSource2() {
DriverManagerDataSource dataSource2 = new DriverManagerDataSource();
dataSource2.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName2"));
dataSource2.setUrl(environment.getRequiredProperty("jdbc.url2"));
dataSource2.setUsername(environment.getRequiredProperty("jdbc.username2"));
dataSource2.setPassword(environment.getRequiredProperty("jdbc.password2"));
return dataSource2;
}
#Autowired
#Qualifier(value = "sessionFactory2")
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager2 = new HibernateTransactionManager();
txManager2.setSessionFactory(s);
return txManager2;
}
}
Second Configuration :
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:hibernate.properties" })
public class RepositoryConfiguration {
#Autowired
private Environment environment;
#Bean(name="sessionFactory")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setHibernateProperties(hibernateProperties());
sessionFactory.setPackagesToScan(new String[] { "com.project" });
return sessionFactory;
}
#Bean
public Properties hibernateProperties() {
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.hbm2ddl.auto", "update");// environment.getRequiredProperty("hibernate.hbm2ddl.auto")
return properties;
}
#Bean(name = "datasource")
public DataSource dataSource() {
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;
}
#Bean
#Autowired
#Qualifier(value = "sessionFactory")
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}

Ok so, I did more R&D and with luck i solved the problem..
So here's what i did
Merged my RepositoryConfiguration into one class.
Removed Autowired from HibernateTransactionManager and manually wired sessionFactories.
Also cjanged packages to scan for hibernate(realized it will create same tables in both databases)
Add qualifier in #Transactional(import from spring.)
#Transactional("sessionFactoryTransactionManager")
in my repositories.
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:hibernate.properties" })
public class RepositoryConfiguration {
#Autowired
private Environment environment;
#Bean(name = "sessionFactory")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setHibernateProperties(hibernateProperties());
sessionFactory.setPackagesToScan(new String[] { "com.project" });
return sessionFactory;
}
#Bean
public Properties hibernateProperties() {
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.hbm2ddl.auto", "update");// environment.getRequiredProperty("hibernate.hbm2ddl.auto")
return properties;
}
#Bean(name = "sessionFactory2")
public LocalSessionFactoryBean sessionFactory2() {
LocalSessionFactoryBean sessionFactory2 = new LocalSessionFactoryBean();
sessionFactory2.setDataSource(dataSource());
sessionFactory2.setHibernateProperties(hibernateProperties2());
sessionFactory2.setPackagesToScan(new String[] { "com.server" });
return sessionFactory2;
}
#Bean
public Properties hibernateProperties2() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect2"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql2"));
properties.put("hibernate.hbm2ddl.auto", "update2");// environment.getRequiredProperty("hibernate.hbm2ddl.auto")
return properties;
}
#Bean(name = "datasource2")
public DataSource dataSource2() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName2"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url2"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username2"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password2"));
return dataSource;
}
#Bean(name = "datasource")
public DataSource dataSource() {
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;
}
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
#Autowired
#Qualifier("sessionFactory2")
private SessionFactory sessionFactory2;
#Bean(name = "sessionFactoryTransactionManager")
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(this.sessionFactory);
return txManager;
}
#Bean(name = "sessionFactory2TransactionManager")
public HibernateTransactionManager transactionManager2() {
HibernateTransactionManager txManager2 = new HibernateTransactionManager();
txManager2.setSessionFactory(this.sessionFactory2);
return txManager2;
}
}

Related

hibernate5 + spring boot connect multiple databases

I want to use hibernate to connect two different databases and use different sessionfactory to operate the data
In the example below , Another datasource and LocalSessionFactoryBean will be added in the #Configuration class , but how do I give these two sessionFactory specific names?
Reference:
https://www.baeldung.com/hibernate-5-spring
#Configuration
#EnableTransactionManagement
public class HibernateConf {
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(
{"com.baeldung.hibernate.bootstrap.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:db;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa");
dataSource.setPassword("sa");
return dataSource;
}
#Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty(
"hibernate.hbm2ddl.auto", "create-drop");
hibernateProperties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.H2Dialect");
return hibernateProperties;
}
}
Want to reach the effect:
#Service
#Transactional
public class TestRepositoryImpl implements TestRepository{
#Qualifier("connectionA")
#Autowired
private SessionFactory sessionFactory;
#Qualifier("connectionB")
#Autowired
private SessionFactory sessionFactory;
...
...
}
Another project example:
#Configuration
public class DataSourceConfig {
#Primary
#Bean(name = "test1DataSource")
#ConfigurationProperties(prefix = "spring.datasource.test1")
public DataSource test1DataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "test2DataSource")
#ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource test2DataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Autowired
#Bean(name = "test1Connection")
public NamedParameterJdbcTemplate test1JdbcTemplate(#Qualifier("test1DataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Autowired
#Bean(name ="test2Connection")
public NamedParameterJdbcTemplate test2JdbcTemplate(#Qualifier("test2DataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
}
Any help is greatly appreciated!
If you want to achieve hibernate with two Database: use session factory like below.
But i recommend use Spring Data JPA it will give more specification and easier to understand.
public class Transfer {
public static void main(String[] args) {
// get the SessionFacotry
SessionFactory connectionAFactory = HibernateConf.getSessionFactory();
SessionFactory connectionBFactory= DataSourceConfig.getSessionFactory();
// get The Session
Session connectionASes = HibernateConf.getSession();
Session connectionBSes = DataSourceConfig.getSession();
For this you can configure your data connection beans like this:
#Configuration
public class DataSourceConfig {
#Primary
#Bean(name = "test1DataSource")
#ConfigurationProperties(prefix = "spring.datasource.test1")
public DataSource test1DataSource() {
return DataSourceBuilder.create().build();
}
#Bean(name = "test2DataSource")
#ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource test2DataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Autowired
#Bean(name = "test1Connection")
public NamedParameterJdbcTemplate test1JdbcTemplate(#Qualifier("test1DataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Autowired
#Bean(name ="test2Connection")
public NamedParameterJdbcTemplate test2JdbcTemplate(#Qualifier("test2DataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
}
After that you can autowire them separately by using #Qualifier in following way in your service class:
#Service
#Transactional
public class TestRepositoryImpl implements TestRepository{
#Qualifier("test1Connection")
#Autowired
private SessionFactory sessionFactory1;
#Qualifier("test2Connection")
#Autowired
private SessionFactory sessionFactory2;
...
...
}

Can't map class to Hibernate without xml with ".setAnnotatedClasses()" Getting "2QuerySyntaxException: FileEntity is not mapped" error

Hi everyone.
I am trying to map class (FileEntity) to Hibernate using .setAnnotatedClasses() or .setPackagesToScan() methods. But I get the same error over and over again.
org.hibernate.hql.internal.ast.QuerySyntaxException: FileEntity is not mapped
When I mapped the class with .xml all worked fine.
Please tell me, where is my mistake?
ApplicationContextConfig.java
#Configuration
#ComponentScan("com.group.appName")
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class ApplicationContextConfig {
#Autowired
Environment environment;
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
return new InternalResourceViewResolver();
}
#Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(environment.getProperty("spring.datasource.url"));
dataSource.setUsername(environment.getProperty("spring.datasource.username"));
dataSource.setPassword(environment.getProperty("spring.datasource.password"));
return dataSource;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(#Qualifier("dataSource") DataSource dataSource) throws Exception {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getProperty("spring.jpa.properties.hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getProperty("spring.jpa.show-sql"));
properties.put("current_session_context_class", environment.getProperty("spring.jpa.properties.hibernate.current_session_context_class"));
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setHibernateProperties(properties);
factoryBean.afterPropertiesSet();
factoryBean.setPackagesToScan("com.group.appName.model");
// or another method
factoryBean.setAnnotatedClasses(FileEntity.class);
return factoryBean.getObject();
}
#Autowired
#Bean(name = "transactionManager" )
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager
= new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
#Bean(name = "multipartResolver")
public CommonsMultipartResolver getCommonsMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(20971520); // 20MB
multipartResolver.setMaxInMemorySize(1048576); // 1MB
return multipartResolver;
}
}
FileEntity.java
#Entity
#Table(name ="files_upload")
public class FileEntity {
private String fileName;
private Byte[] fileData;
#Id
#Column(name = "file_name")
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
#Column(name = "file_data")
public Byte [] getFileData() {
return fileData;
}
public void setFileData(Byte [] fileData) {
this.fileData = fileData;
}
}
application.properties
server.port=9090
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/filedb?serverTimezone=Europe/Moscow
spring.datasource.username=root
spring.datasource.password=241299
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
Ok. I fixed it.
The point is that in method getSessionFactory after creating an object of class LocalSessionFactoryBean the first line should be
factoryBean.setAnnotatedClasses(FileEntity.class);
So the correct creating an object of LocalSessionFactoryBean class is:
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setAnnotatedClasses(FileEntity.class); - first line.
factoryBean.setDataSource(dataSource);
factoryBean.setHibernateProperties(properties);
factoryBean.afterPropertiesSet();

Spring JPA and Hibernate do not save entity to database when calling save method [duplicate]

This question already has an answer here:
JpaRepository won't save data
(1 answer)
Closed 2 years ago.
I have a problem creating a Spring project using Spring Data JPA and Hibernate. When I called save method on the repository, it didn't insert my object to the database.
Hibernate config class:
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.app.config" })
#PropertySource(value = { "classpath:application.properties" })
#EnableJpaRepositories(basePackages = { "com.app.repository" })
public class HibernateConfiguration {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.app.model", "com.app.repository" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(new String[] { "com.app.model", "com.app.repository" });
factory.setDataSource(dataSource());
factory.setJpaProperties(hibernateProperties());
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public DataSource dataSource() {
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;
}
#Bean
#Autowired
public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory) {
HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
return hibernateTemplate;
}
private Properties hibernateProperties() {
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;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
#Autowired
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
}
Repository class:
#Repository
public interface CityRepository extends BaseRepository<City, Integer> {
City findByName(String name);
List<City> findAll();
#Query("SELECT c.name FROM City c")
List<String> findAllCityName();
}
Service class:
#Service
public class CityService {
#Autowired
private CityRepository cityRepository;
public void saveCity(City city) {
return cityRepository.save(city);
}
}
BaseRepository is extended by CrudRepository in Spring JPA.
The code above runs without any errors but entity was not saved to the DB. Does anyone know what the issue with my code is?
I've resolved my problem by follow answer from JB Nizet above.
Drop the sessionFactory, drop the hibernateTemplate, replace the HibernateTransactionManager by a JpaTransactionManager. – JB Nizet

Could not autowire field JpaUserRepository (JpaRepository)

I try to connect JpaRepository to work with Hibernate.
But I cannot autowire it like this.
I see error: Could not autowire field JpaUserRepository.
#Autowired
private JpaUserRepository jpaUserRepository;
My Repository:
public interface JpaUserRepository extends JpaRepository<User, Integer> {
}
What I missed?
My HibernateConfig:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "com.springapp.mvc.repositories")
public class HibernateConfig {
#Bean
public DriverManagerDataSource dataSource(){
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("org.postgresql.Driver");
driverManagerDataSource.setUrl("jdbc:postgresql://localhost:5432");
driverManagerDataSource.setUsername("postgres");
driverManagerDataSource.setPassword("password");
return driverManagerDataSource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPersistenceUnitName("jpaData");
factoryBean.setJpaVendorAdapter(hibernateJpaVendorAdapter());
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
factoryBean.setJpaProperties(properties);
factoryBean.setPackagesToScan(new String[]{"com.springapp.mvc.models"});
return factoryBean;
}
#Bean
public JpaTransactionManager transactionManager(){
JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
jpaTransactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return jpaTransactionManager;
}
#Bean
public HibernateJpaVendorAdapter hibernateJpaVendorAdapter(){
return new HibernateJpaVendorAdapter();
}
}
I found solution myself. I upgraded spring to version 4.1.7 and it works.

How to set up hbm2ddl.auto with pure java configuration

I am having a hard time finding materials which explain and outline on how to set up hbm2ddl.auto with pure java configuration in Spring 4.
I am not using Spring Boot, as I want to get more understanding of Spring fundamentals. But of course, I want to avoid all XML files in my application.
So far I am able to configure and use my application, but I have to create tables manually. My attempt to set up hbm2ddl.auto is not going anywhere.
This is what I have:
#Configuration
#EnableTransactionManagement
public class DataSourceConfiguration {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "com.mysql.jdbc.Driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Autowired
private Environment env;
#Bean
public DataSource dataSource() throws SQLException {
System.out.println("--------------");
System.out.println("Data Source Initialization");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myeventmanager");
dataSource.setUsername("root");
dataSource.setPassword("******");
System.out.println("--------------");
System.out.println("Initialized");
System.out.println(dataSource.getConnection());
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setPackagesToScan(new String[]{"com.ruruapps.domain"});
Properties props = new Properties();
props.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
sessionFactoryBean.setHibernateProperties(props);
return sessionFactoryBean;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
#Bean
public BeanPostProcessor persistenceTranslation() {
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");
}
};
}
}
So what is the right way to have this configured?
You can implement as follows.
#Configuration
#EnableTransactionManagement
#ComponentScan({ "xxx.xxx.xxx" })
#PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.ws.ppp.pojo" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean(name = "dataSource")
public DataSource dataSource() {
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 hibernateProperties() {
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.automaticschema"));
properties.put("hibernate.search.default.directory_provider",
environment.getRequiredProperty("hibernate.search.default.directory_provider"));
properties.put("hibernate.search.default.indexBase",
environment.getRequiredProperty("hibernate.search.default.indexBase"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
It will be like .
private Properties hibernateProperties() {
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.automaticschema"));
properties.put("hibernate.search.default.directory_provider",
environment.getRequiredProperty("hibernate.search.default.directory_provider"));
properties.put("hibernate.search.default.indexBase",
environment.getRequiredProperty("hibernate.search.default.indexBase"));
return properties;
}
try this.

Categories