I have next working code with ddl and dml. Its initialize embedded H2 database.
#Bean
public DataSource dataSource(#Value("${jdbc.driver}") String driver,
#Value("${jdbc.url}") String url,
#Value("${jdbc.user}") String user,
#Value("${jdbc.password}") String password) {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
Resource initSchema = new ClassPathResource("schema.sql");
Resource initData = new ClassPathResource("data.sql");
DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
DatabasePopulatorUtils.execute(databasePopulator, dataSource);
return dataSource;
}
#Bean
public EntityManagerFactory entityManagerFactory(DataSource dataSource) {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(false);
jpaVendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean entityManagerFactory =
new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
entityManagerFactory.setPackagesToScan("org.doit.model");
entityManagerFactory.afterPropertiesSet();
return entityManagerFactory.getObject();
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
Pls give me advise, how to insert in database the binary data, like a zip file that is located in the resource folder.
I know that in unit test we can use annotation #Before which give us opportunity to do what you want. But how do it when you start your app with java config.
I have also faced the same issue.
This answer worked for me. You can try it, I think this will work for you.
Related
We have a case where we connect to different databases environments, but the tables in each of the environment are the same.
Is there any way I can reuse the entity class for each of the environment?
I am using separate config class for each of the environment. Below is the config for one of the environment, similarly I have 4 others. The "packages" deduce which environment to connect to.
codejava
#Configuration
#EnableJpaRepositories(basePackages = {"packages"},
entityManagerFactoryRef = "OneEntityManager",
transactionManagerRef = "OneTransactionManager")
public class DevDataSourceConfig {
#Bean
#Primary
public LocalContainerEntityManagerFactoryBean OneEntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(OneDataSource());
em.setPackagesToScan(String[]{"packages"});
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
em.setJpaPropertyMap(properties);
return em;
}
#Primary
#Bean
public DataSource OneDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverclass);
dataSource.setUrl(url);
dataSource.setUsername(uName);
dataSource.setPassword(dbPass);
return dataSource;
}
#Primary
#Bean
public PlatformTransactionManager OneTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(OneEntityManager().getObject());
return transactionManager;
}
}
I am getting this error while running my application : org.hibernate.service.UnknownUnwrapTypeException: Cannot unwrap to requested type [javax.sql.DataSource]
My configuration class :
#Configuration
#PropertySource("classpath:META-INF/spring/jdbc.properties")
public class HibernateConfig {
#Autowired
private Environment env;
#Bean(name="dataSource")
public DataSource getDataSource() throws PropertyVetoException{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(env.getProperty("db.driverClass"));
dataSource.setJdbcUrl(env.getProperty("db.jdbcUrl"));
dataSource.setUser(env.getProperty("db.user"));
dataSource.setPassword(env.getProperty("db.password"));
dataSource.setMaxPoolSize(50);
dataSource.setMinPoolSize(5);
dataSource.setMaxConnectionAge(1800);
dataSource.setMaxIdleTime(1800);
dataSource.setAutoCommitOnClose(false);
dataSource.setInitialPoolSize(5);
return dataSource;
}
#Bean(name="sessionFactory")
#Scope("singleton")
public LocalSessionFactoryBean getSessionFactory(DataSource dataSource){
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("db.dialect"));
hibernateProperties.setProperty("hibernate.jdbc.batch_size", "0");
hibernateProperties.setProperty("c3p0.acquire_increment", "1");
localSessionFactoryBean.setHibernateProperties(hibernateProperties);
return localSessionFactoryBean;
}
#Bean(name="transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory){
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
}
I ran actually into this thread which talks about the same issue. However I am wondering if it is a sort of bug in hibernate5 that has not been fixed yet or does it relate to something else. Thank you in advance.
I am trying to deploy my web app to Heroku. I have configured Hibernates (as the persistence provider) to do the following:
create schema based on entities;
fill data from sql script;
Here is my configuration:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(getDataSource());
entityManagerFactoryBean.setPackagesToScan("model");
entityManagerFactoryBean.setPersistenceProvider(new HibernatePersistenceProvider());
entityManagerFactoryBean.setJpaProperties(getHibernateProperties());
return entityManagerFactoryBean;
}
#Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setDataSource(getDataSource());
return transactionManager;
}
#Bean
public DataSource getDataSource() {
String dbUrl = System.getenv("JDBC_DATABASE_URL");
String username = System.getenv("JDBC_DATABASE_USERNAME");
String password = System.getenv("JDBC_DATABASE_PASSWORD");
BasicDataSource basicDataSource = new BasicDataSource();
basicDataSource.setUrl(dbUrl);
basicDataSource.setUsername(username);
basicDataSource.setPassword(password);
return basicDataSource;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
properties.setProperty("hibernate.hbm2ddl.import_files", "test_data.sql");
return properties;
}
However, it seems that Hibernate cannot alter existing Heroku schema:
2016-07-16T15:04:20.978399+00:00 app[web.1]: 2016-07-16 15:04:20 ERROR SchemaExport:483 - HHH000389: Unsuccessful: alter table fueling drop constraint fuel_type
2016-07-16T15:04:20.975268+00:00 app[web.1]: 2016-07-16 15:04:20 ERROR SchemaExport:484 - ERROR: relation "customer" does not exist
2016-07-16T15:04:20.985169+00:00 app[web.1]: 2016-07-16 15:04:20 ERROR SchemaExport:484 - ERROR: relation "fueling" does not exist
Could you please advise what I am doing wrong?
I am trying to model it off of this example https://github.com/spring-projects/spring-data-examples/tree/master/jpa/multiple-datasources but they dont seem to be using a properties file, which is confusing me. How do they input the database name, log in info, and url? The way I currently have it is like this:
This is my config file for one of my databases: LM_Config.java
#Configuration
#EnableJpaRepositories(entityManagerFactoryRef = "lmEntityManagerFactory",
transactionManagerRef = "lmTransactionManager")
class LM_Config {
#Bean
PlatformTransactionManager lmTransactionManager() {
return new JpaTransactionManager(lmEntityManagerFactory().getObject());
}
#Bean
LocalContainerEntityManagerFactoryBean lmEntityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(lmDataSource());
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setPackagesToScan(LM_Config.class.getPackage().getName());
return factoryBean;
}
#Bean
#Primary
#ConfigurationProperties(prefix="spring.datasource")
public DataSource lmDataSource() {
return DataSourceBuilder.create().build();
}
}
This is my config file for one of my databases: MTS_Config.java
#Configuration
#EnableJpaRepositories(entityManagerFactoryRef = "mtsEntityManagerFactory",
transactionManagerRef = "mtsTransactionManager")
class MTS_Config {
#Bean
PlatformTransactionManager mtsTransactionManager() {
return new JpaTransactionManager(mtsEntityManagerFactory().getObject());
}
#Bean
LocalContainerEntityManagerFactoryBean mtsEntityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(mtsDataSource());
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setPackagesToScan(MTS_Config.class.getPackage().getName());
return factoryBean;
}
#Bean
#Primary
#ConfigurationProperties(prefix="spring.mtsDatasource")
public DataSource mtsDataSource() {
return DataSourceBuilder.create().build();
}
}
This is my application.properties file. The main points of interest should be the ones starting in spring.datasource... and spring.mtsDatasource...
hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.default_schema=dbo
hibernate.packagesToScan=src.repositories.LMClientRepository.java
spring.jpa.generate-ddl=true
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.DefaultNamingStrategy
spring.datasource.username=LOADdev
spring.datasource.password=lmtdev01
spring.datasource.url=jdbc:sqlserver://schqvsqlaod:1433;database=dbMOBClientTemp;integratedSecurity=false;
spring.datasource.testOnBorrow=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.database=dbMOBClientTemp
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
#spring.jpa.hibernate.ddl-auto=none
#spring.jpa.hibernate.ddl-auto=none
#spring.jpa.properties.hibernate.hbm2ddl.auto=none
spring.mtsDatasource.username=mtsj
spring.mtsDatasource.password=mtsjapps
spring.mtsDatasource.url=jdbc:sqlserver://SCHQVSQLCON2\VSPD:1433;database=dbMTS;integratedSecurity=false;
spring.mtsDatasource.testOnBorrow=true
spring.mtsDatasource.validationQuery=SELECT 1
they dont seem to be using a properties file, which is confusing me. How do they input the database name, log in info, and url?
The answer to this is that the example is using an embedded database, so there is no DB name, username, etc..
For your main question, review the similar questions in the sidebar, look at the documentation for #Qualifier, and come back with a more specific question.
I am using java-play-spring template (obtainable here: https://github.com/jamesward/play-java-spring#master )and currently I am trying to write some evolutions for it.
I am putting my script:
# --- !Ups
CREATE TABLE accounts
(
accountid INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
clientid INT NOT NULL,
credit DECIMAL(13,2)
);
# --- !Downs
drop table accounts;
into conf/evolutions/default/1.sql. Unfortunatelly, after application starts, nothing happens. I suppose that it may be Spring/Hibernate fault, so i disabled Hibernate validation:
#Configuration
#EnableTransactionManagement
public class DataConfig {
#Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
vendorAdapter.setGenerateDdl(false);
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
entityManagerFactory.setPackagesToScan("models");
entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
entityManagerFactory.setDataSource(dataSource());
entityManagerFactory.setValidationMode(ValidationMode.NONE);
entityManagerFactory.afterPropertiesSet();
return entityManagerFactory.getObject();
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager(entityManagerFactory());
return transactionManager;
}
#Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(Play.application().configuration().getString("db.default.driver"));
dataSource.setUrl(Play.application().configuration().getString("db.default.url"));
dataSource.setUsername(Play.application().configuration().getString("db.default.user"));
dataSource.setPassword(Play.application().configuration().getString("db.default.password"));
return dataSource;
}
}
But this didn't help. I have also added
play.modules.evolutions.enabled=true
To my application.conf. This does not help too.
Does anyone has any ideas what may be wrong?