I am using hibernate-validator 5.1.2.Final and Spring 4.0.6.RELEASE and want to make use of fail-fast so that when I have configured an annotation with multiple constraints, they are not all executed and only the first error message is returned.
#MultipartFileNotEmpty
#CsvFile
#Documented
#Constraint(validatedBy = { })
#Target(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME)
public #interface OrderCsv {
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
From looking at the Hibernate Validator docs it appears I can enable fail_fast at a global level, but I am unsure how to enable this within Java config. My current hibernate configuration looks like:
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages="uk.co.project")
public class HibernateConfig {
final static String JDBC_URL = "jdbc:mysql://localhost:3306/";
final static String DRIVER_CLASS = "com.mysql.jdbc.Driver";
#Autowired
private Environment environment;
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new org.apache.commons.dbcp2.BasicDataSource();
dataSource.setDriverClassName(DRIVER_CLASS);
dataSource.setUsername(environment.getProperty("datasource.username"));
dataSource.setPassword(environment.getProperty("datasource.password"));
dataSource.setUrl(JDBC_URL + environment.getProperty("datasource.database"));
dataSource.setInitialSize(10);
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "uk.co.project.models" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties hibernateProperties() {
return new Properties() {
private static final long serialVersionUID = 1L;
{
setProperty("hibernate.hbm2ddl.auto", "validate");
setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
setProperty("hibernate.globally_quoted_identifiers", "true");
setProperty("hibernate.show_sql", "true");
}
};
}
}
I have tried adding setProperty("hibernate.validator.fail_fast", "true"); to my hibernateProperties but that did not work. I would appreciate any pointers on how to enable fail_fast within my hibernate java config.
"hibernate.validator.fail_fast" property is not the property of sessionFactory it is property for ValidatorFactory, you can try something like this:
#Bean
public LocalValidatorFactoryBean getValidatorFactory() {
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
localValidatorFactoryBean.getValidationPropertyMap().put("hibernate.validator.fail_fast", "true");
return localValidatorFactoryBean;
}
Related
Here is my PersistanceConfiguration from my Spring Boot app.
#Configuration
#EnableAspectJAutoProxy
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"org.persistence.repository"},
transactionManagerRef = "jpaTransactionManager",
entityManagerFactoryRef = "entityManagerFactory")
#ComponentScan("org.persistence")
public class PersistenceConfiguration {
private static final Logger LOG = LoggerFactory.getLogger(PersistenceConfiguration.class);
#Autowired
private ResourceLoader resourceLoader;
#Autowired
private AuditInterceptor auditInterceptor;
#Autowired
private DataSource dataSource;
#Autowired
private HibernateProperties hibernateProperties;
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Primary
#Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sf = new LocalSessionFactoryBean();
sf.setDataSource(this.dataSource);
sf.setMappingLocations(getMappingLocations());
sf.setHibernateProperties(getHibernateProperties());
sf.setEntityInterceptor(auditInterceptor);
sf.setAnnotatedClasses(getAnnotedClass());
return sf;
}
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean bean = new LocalContainerEntityManagerFactoryBean();
bean.setPackagesToScan("org.domain.entity");
HibernateJpaVendorAdapter hjva = new HibernateJpaVendorAdapter();
bean.setJpaVendorAdapter(hjva);
bean.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
bean.setDataSource(this.dataSource);
bean.setJpaProperties(getHibernateProperties());
return bean;
}
#Bean(name = "entityManager")
public EntityManager entityManager(EntityManagerFactory myEntityManagerFactory) {
return myEntityManagerFactory.createEntityManager();
}
#Bean(name = "jpaTransactionManager")
#Order(3)
public PlatformTransactionManager jpaTransactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
#Primary
#Bean
#Order(2)
public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) {
final HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory);
return htm;
}
#Bean
public Properties getHibernateProperties() {
final Properties properties = new Properties();
// SQL dialect
properties.put("hibernate.dialect", this.hibernateProperties.getDialect());
// Second-level cache
properties.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
properties.put("hibernate.cache.use_second_level_cache", "true");
properties.put("hibernate.cache.use_query_cache", "true");
properties.put("hibernate.cache.ehcache.missing_cache_strategy", "create");
properties.put("hibernate.cache.provider_class", "org.hibernate.cache.EhCacheProvider");
properties.put("net.sf.ehcache.configurationResourceName", "/ehcache.xml");
// Echo all executed formated SQL to stdout - False en production
properties.put("hibernate.show_sql", this.hibernateProperties.getShowSql());
properties.put("hibernate.format_sql", this.hibernateProperties.getFormatSql());
LOG.info("RepositoryConfiguration.HibernateProperties: {}", properties);
return properties;
}
It perfectly works when I launch my app, for context I need to have an Hibernate sessionManager for the legacy code, and a EntityManager to use JPARepository in my new code.
The problem comes when I try to launch my tests. If I use a JPARepository method like a simple findById, nothing is found, but when I use a criteria from sessionManager, it finds the correct data.
I think my EntityManager is not properly connected for my tests, but I don't really know where to look at, I don't have xml configuration, just this.
/**
* The Class IntegrationTestConfiguration.
*/
#Configuration
#ComponentScan("org.test")
#PropertySource(value = "classpath:/application.properties", ignoreResourceNotFound = true)
#PropertySource(value = "classpath:/conf/variables.properties", ignoreResourceNotFound = true)
public class IntegrationTestConfiguration {
/** The data source. */
#Autowired
private DataSource dataSource;
/** The flyway properties. */
#Autowired
private FlywayProperties flywayProperties;
/**
* Sql data type factory.
*
* #return the postgresql data type factory
*/
#Bean
public PostgresqlDataTypeFactory sqlDataTypeFactory() {
return new PostgresqlDataTypeFactory();
}
/**
* Db unit database config.
*
* #return the database config bean
*/
#Bean
public DatabaseConfigBean dbUnitDatabaseConfig() {
final DatabaseConfigBean dbConf = new DatabaseConfigBean();
dbConf.setDatatypeFactory(sqlDataTypeFactory());
return dbConf;
}
/**
* Db unit database connection.
*
* #return the database data source connection factory bean
*/
#Bean
public DatabaseDataSourceConnectionFactoryBean dbUnitDatabaseConnection() {
final DatabaseDataSourceConnectionFactoryBean dbDsConnection = new DatabaseDataSourceConnectionFactoryBean();
dbDsConnection.setDataSource(dataSource);
dbDsConnection.setDatabaseConfig(dbUnitDatabaseConfig());
return dbDsConnection;
}
/**
* Flyway.
*
* #return the flyway
*/
#Bean
public Flyway flyway() {
final FluentConfiguration conf = Flyway.configure();
conf.dataSource(dataSource);
conf.schemas(flywayProperties.getSchemas());
conf.baselineOnMigrate(flywayProperties.getBaselineOnMigrate());
conf.baselineVersion(flywayProperties.getBaselineVersion());
final Flyway flyway = new Flyway(conf);
flyway.migrate();
return flyway;
}
#Bean
public JavaMailSender getJavaMailSender() {
final JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
final Properties props = mailSender.getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
return mailSender;
}
}
And here is my problem, how can I plug my entityManager to the sessionManager or the database and have access to my data during my tests?
An example of a test with JUnit:
#Test
#Transactional
#DatabaseSetup(value = {
"/dataset/input/programme/referent.xml" })
public void testChargerUnReferent(){
//GIVEN
ReferentDTO referentDTO;
//WHEN
referentDTO = referentService.chargerReferent(11L);
//THEN
Assert.assertEquals(Long.valueOf(11), referentDTO.getId());
Assert.assertEquals(EnumReferentielReferent.ADEME, referentDTO.getType());
Assert.assertEquals("Ademe1", referentDTO.getLibelle());
}
I wanted to make REST Api using Spring.
I have added Tomcat in Run/Debug Configurations.
Here is my Config class
#Configuration
#ComponentScan("com.dashkindima.blog.mvc")
#EnableWebMvc
#EnableTransactionManagement
public class MyConfig {
#Bean
public DataSource dataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/reeve?autoReconnect=true&allowMultiQueries=true&useSSL=false&useUnicode=true&&characterEncoding=UTF8");
dataSource.setUser("root");
dataSource.setPassword("1234");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("com.dashkindima.blog.mvc.hibernatetest.entity");
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
sessionFactory.setHibernateProperties(hibernateProperties);
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
I have also defined WebInitializer class
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{MyConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/*"};
}
}
I have tried almost all urls in #RequestMapping like /api , /{app_name}/api but nothing happens.
#RestController
#RequestMapping("/blog/api")
public class MyRESTController {
#Autowired
private LivingComplexService livingComplexService;
#GetMapping("/living")
public List<LivingComplex> showAllLivingComplexes(){
List<LivingComplex> allComplexes = livingComplexService.getAllComplexes();
return allComplexes;
}
}
You can be sure that Service will return livingComplexes. So the problem is in Tomcat.
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
I'm trying to retrieve data from application.properties file using Environment in my Spring Application but it's not working. I cant get the data bound correctly by Environment. I only can get this working if I use local variables as shown below:
AppConfig.class now!
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("com.victommasi.eshop.dao")
#PropertySource("classpath:application.properties")
public class AppConfig {
private static final String driverClass = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost/eshop";
private static final String username = "root";
private static final String password = "root";
private static final String dialect = "org.hibernate.dialect.MySQL5Dialect";
private static final String showSql = "true";
private static final String formatSql = "true";
private static final String hbm2dllAuto = "update";
private static final String packageToScan = "com.victommasi.eshop.model";
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", dialect);
properties.put("hibernate.show_sql", showSql);
properties.put("hibernate.format_sql", formatSql);
properties.put("hibernate.hbm2ddl.auto", hbm2dllAuto);
return properties;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProvider(new HibernatePersistenceProvider());
entityManagerFactoryBean.setPackagesToScan(packageToScan);
entityManagerFactoryBean.setJpaProperties(hibernateProperties());
return entityManagerFactoryBean;
}
}
AppConfig.class as I want
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("com.victommasi.eshop.dao")
#PropertySource("classpath:application.properties")
public class AppConfig {
#Autowired
private Environment env;
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClass"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProvider(new HibernatePersistenceProvider());
entityManagerFactoryBean.setPackagesToScan(env.getProperty("packages.to.scan"));
entityManagerFactoryBean.setJpaProperties(hibernateProperties());
return entityManagerFactoryBean;
}
Other classes:
WebConfig.class
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = { "com.victommasi.eshop" })
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setContentType("text/html;charset=UTF-8");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean(name = "filterMultipartResolver")
public CommonsMultipartResolver getMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1048576);
multipartResolver.setMaxInMemorySize(1048576);
return multipartResolver;
}
}
WebAppInitializer.class
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebConfig.class, AppConfig.class, SecurityConfig.class);
container.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
I know it seems to be a very easy, I have also followed this tutorial, but cant get this done.
I didn't go through it all but it seems like you're missing the PropertySourcesPlaceholderConfigurer bean
Since Spring 3.1 introduced the new #PropertySource annotation, as a
convenient mechanism of adding property sources to the environment.
This annotation is to be used in conjunction with Java based
configuration and the #Configuration annotation:
#Configuration
#PropertySource("classpath:application.properties")
public class AppConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
With that, you can now start injecting a property with the #Value annotation is straightforward:
#Value( "${jdbc.url}" )
private String jdbcUrl;
On the other note, consider/look into spring-boot , you'll get all the above (including all the code you have shared)and much more out for free i.e with zero line of code
After reading a comment I took a look at console and found that data in 'application.properties' file were binded to AppConfig.class by Environment with blank spaces.
Stacktrace:
Caused by: java.sql.SQLException: Access denied for user 'root '#'localhost'
I assume it was the reason the binding wasn't working. My application is now working as I wanted. Thanks.
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.