Spring H2 embedded database [duplicate] - java

This question already has answers here:
Does Spring embedded database support different SQL dialects?
(3 answers)
Closed 5 years ago.
I want to create an in-memory database populated with test data for fast testing, so I declare this bean in my configuration file, but I also want so set this properties:
MODE=MySQL
DB_CLOSE_ON_EXIT=FALSE
but I don't know where to do it
#Bean
public DataSource dataSource(){
return
(new EmbeddedDatabaseBuilder())
.setType(EmbeddedDatabaseType.H2) //.H2
.addScript("classpath:db/H2.schema.sql")
.addScript("classpath:db/H2.data.sql")
.build();
}

try this
#Bean
public DataSource dataSource(){
return
new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.setName("testDB;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL")
.addScript("classpath:db/H2.schema.sql")
.addScript("classpath:db/H2.data.sql")
.build();
}

You can try using EmbeddedDatabaseBuilder.setName()
#Bean
public DataSource dataSource() {
return
new EmbeddedDatabaseBuilder()
.setName("testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=false")
.setType(EmbeddedDatabaseType.H2) //.H2
.addScript("classpath:db/H2.schema.sql")
.addScript("classpath:db/H2.data.sql")
.build();
}
Note: I have not tried this myself, but found a clue on this answer

An alternative approach is to wire DataSources using properties. This way, you can set the JDBC URL which can contain additional properties.

The mode can be done via a SQL statement on H2, but I am pretty sure the DB_CLOSE_DELAY must be set as part of the URL which there is no easy hook into. You would be best just setting this in the application.properties/yml and let spring autoconfigure it
jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;MODE=MySQL would be the spring.datasource.url additional properties are available for the schema and data

Related

Object initialization error SimpleDriverDataSource object with MongoDB

I need to set SimpleDriverDataSource object in order to create datasource with MongoDB, however I am not able to figure out what I should pass as "Driver".
I searched and found out that this is the JDBC driver for MongoDB "mongodb.jdbc.MongoDriver", but how do I set it up while initializing SimpleDriverDataSource object?
I have tried doing the below, but it shows error mentioned below
#Bean
protected DataSource dataSource() {
SimpleDriverDataSource ds = new SimpleDriverDataSource();
Driver driver = new Driver("mongodb.jdbc.MongoDriver");
ds.setDriverClass(driver);
ds.setUrl("jdbc:mongodb://localhost:27017:spring-security-sampledb");
ds.setUsername("root");
ds.setPassword("secret");
return ds;
}
error
Cannot instantiate the type Driver
I am new to Spring Boot. Can you please help me in implementing this?
java.sql.Driver is an interface, which means you cannot instantiate it like that. You may want to review the basics of Java before starting with Spring Boot.
In any case, you need to use new mongodb.jdbc.MongoDriver() instead of new Driver(), or use setDriverClass and pass it the class reference (mongodb.jdbc.MongoDriver.class) instead of a Driver instance.
Also, please be aware that SimpleDriverDataSource is probably the wrong choice, as - for example - it doesn't provide connection pooling.

Spring Transaction Manager and DataSource Java Config way to pass same bean id without creating a new instance

Goal
I want to introduce a transaction manage on my data source.
Looking for the correct way to use same instance of datasource for the transaction manager as well. My requirement is specify to Java Config way to pass the "Same instance" of DS to Transaction Manager. Correct me If there is a gap in my understanding.
In my case I have a datasource and of type autocommit false, and by using the Transaction Manager specified below, I want to commit/rollback a transaction (e.g. Update an operation/Revert an Update operation ---when there a error/no error in the transaction).
However, while debugging I have noticed that when I used java config specified below, I get two different instance of data source and trx.commit() does not work.
Programmatic transaction management
(https://docs.spring.io/spring/docs/3.0.0.M4/reference/html/ch10s06.html)
#Bean
public DataSource dataSource() {
return getMyDataSource(); //new instance of datasource.//this datasource is autocommit-false
}
#Bean
public DataSourceTransactionManage trxManager() {
return getTransationManage(dataSource()); // this creates another instance of dataSource
}
Any help in this regard is highly appreciated.
Edit :-
I was using Mybatis with Spring. Basically, I had to configure the DataSouce correctly. Below links were useful.
[Pass parameters dynamically to Spring beans ][1] [Mybatis Transaction
Management CTM and PTM ][2] [Spring Transaction Management Notes
][3] [Spring & JTA NOtes][4]
[1]: https://stackoverflow.com/a/21202458/5086633
[2]: http://www.mybatis.org/spring/transactions.html
[3]: https://docs.spring.io/spring/docs/3.0.0.M4/reference/html/ch10s06.html
[4]: https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction
To use back the same instance of dataSource how about you do this:
#Bean
#Autowired
public DataSourceTransactionManage trxManager(DataSource dataSource) {
return getTransationManage(dataSource);
}

Setting the Transaction Isolation Level through Spring Boot properties

I have a spring boot application which I have configured most of the properties through the properties file. However, I was looking if there is a way to set the TRANSACTION_ISOLATION_LEVEL through the Spring boot properties. Could someone help me on this.
I'm initializing the data source bean in the following way:
#Bean
#ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return buildDataSource("spring.datasource");
}
private DataSource buildDataSource(String propPrefix) {
Stirng driverClassName = env.getProperty(propPrefix + ".driver-class-name");
return DataSourceBuilder.create()
.driverClassName(driverClassName)
.build();
}
Could someone please help me on how to specify the TRANSACTION_ISOLATION_LEVEL either through properties or during the data source initialization.
So, the javax.sql.DataSource does not provide a way to set default Transaction Isolation Level. Still, you can do it, but you must strict to particular implementation. Let me give you c couple of examples:
In case you use Apache BasicDataSource implementation of DataSource, then you can use this. This is for DBCP.
If you are using Apache BasicDataSource, but for DBCP2, you can do something like this.
But in most cases, if we are talking about Spring, we use Hikari Connection Pool. So, in case of HikariCP, you can use this method.
The same is applicable to Spring Boot. Let me explain - using Spring Boot properties file, you can set default transaction isolation level, but for specific DataSource, I mean this property:
spring.datasource.hikari.transaction-isolation
as you probably noticed, let you set default transaction isolation level for HikariCP (if you are using one) And this property:
spring.datasource.dbcp2.default-transaction-isolation
allow you to configure default isolation level for DBCP2.
Hope it helped, have a nice day! :)

how to add if else condtion in hibernate configuration file

I am working in spring hibernate project where I am connecting to multiple database. These database details are loaded in a properties file and is imported into hibernate.xml file. Each key was mapped as below.
dbName= dbHost
Mapping as below :
<bean id="dbId" parent="abstractDataSource">
<property name="url" value="${dbName}" />
</bean>
But now i need to include a condition such that the property key to be mapped to multiple values like below
E.g. dbName= statusFlag,dbHost,dbBackupHostName
I need to modify the hibernate configuration file such that using the keyName, corresponding values should be retrieved and splitted with comma separated.
Then I need to check for the statusFlag. If it is true, then i should set the dbValue to 'dbHost', else if the flag is false, it should be set to 'dbBackupHostName'.
Please help me how to implement this condition check in hibernate configuration file.
Also please let me know if this approach is fine to proceed or am i making it too difficult to implement?
Waiting for some valueable answers..
~~~Suriya
To use complex logic in bean wiring and creation in spring you can use Java Configuration
It should work for Spring 3. Sample pseudo code is below.
#Configuration
public class MyCustomConfig {
#Value
String statusFlag;
#Value
String dbHost;
#Value
String dbBackupHostName;
#Bean
public BasicDataSource datasource () {
BasicDataSource datasource = new BasicDataSource();
//Do some custom processing to create datasource
...
return datasource;//return after creation
}
}
Use PropertyPlaceholderConfigurer to load properties as #PropertySource is not available in 3.0.5.
If you can change the spring version to 3.1 which shouldn't make much difference then you can use #Profile along with #PropertySource.
If the logic is not too complex and you can separate set of properties that have to be active at a time. (Local db, Dev db, Prod db, Custom etc.) Then you can try using #Profile.
#Profile annotated bean is created only if that profile is active. A profile can be activated by setting spring.profiles.active.
So to activate the Dev profile we can set in the properties files
spring.profiles.active=dev
//activating 2 profiles
spring.profiles.active=dev,mvc
Below is the sample pseudo code.
#Configuration
#PropertySource("bootstrap.properties")//set spring.profiles.active in it
public class MyCustomConfig {
#Profile("profile1")
public BasicDataSource datasource1 () {
//config using ${profile1.dbName} etc
...
}
#Profile("profile2")
public BasicDataSource datasource2 () {
//config using ${profile2.dbName} etc
...
}
#Profile("profile3")
public BasicDataSource datasource3 () {
//config using ${profile3.dbName} etc
...
}
}

Dynamically select catalog for Tomcat mysql connection pool in a Spring application

I need to create a connection pool from a spring application running in a tomcat server.
This application has many catalogs, the main catalog (its is static) called 'db' has just one table with all existing catalog names and a boolean flag for the "active" one.
When the application starts I need to choose from the main catalogs the active one, then I have to select it as default catalog.
How can I accomplish this?
Until now I used a custom class DataSourceSelector extends DriverManagerDataSource but now I need to improve the db connection using a pool, then I thought about a tomcat dbcp pool.
I would suggest the following steps:
Extend BasicDataSourceFactory to produce customized BasicDataSources.
Those customized BasicDataSources would already know which catalog is active and have the defaultCatalog property set accordingly.
Use your extended BasicDataSourceFactory in the Tomcat configuration.
#Configuration
public class DataAccessConfiguration {
#Bean(destroyMethod = "close")
public javax.sql.DataSource dataSource() {
org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost/db");
ds.setUsername("javauser");
ds.setPassword("");
ds.setInitialSize(5);
ds.setMaxActive(10);
ds.setMaxIdle(5);
ds.setMinIdle(2);
ds.get
return ds;
}
}

Categories