springboot + JDBTemplate (No datasource specified error even though specified in application.properties - spring

Application.properties
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=
i placed this application.properties in resources folder.
Java Class
#Component
public class data{
#Autowired
private JdbcTemplate jdbcTemplate;
public void queryData(){
String sql = "select * from DEPOSIT";
jdbcTemplate = new JdbcTemplate();
jdbcTemplate.execute(sql);
}
}
I am getting
java.lang.Illegal Argument Exception:No Data Source Specified
I am getting this error message even though i specified data source in application.properties
I am using Spring Boot for this task. I Have added almost all the dependencies required in POM.
Not sure why i am not able to access data source. basically trying to access data from DB using Spring boot, MySQL, jdbcTemplate.
Not sure whats wrong here.
Do i have to add anything in the code so that data source can be specified in java class?

Add below properties to your application.properties file. This specifies the data source for your application. Do check if mysql is running on your machine before starting your application.
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.username=yourusername
spring.datasource.password=yourpassword
For additional information refer to below link:
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html

Related

Spring Boot - application creating open, orphan DB connections

In our Spring boot application, we have set the following properties in application.properties
server.port=xxxx
server.servlet.context-path=/
#datasource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://<IP:Port>/<DB Name>
spring.datasource.username=<username>
spring.datasource.password=<pwd>
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.connection.release_mode=after_statement
.....
//Interface using JpaRepository
#Repository
public interface UserlicensesRepo extends JpaRepository<Userlicenses, Integer> {
Optional<Userlicenses> findById(Integer us);
Optional<Userlicenses> findByUsernameAndUserToken(String user, String token);
}
.....
//Using the repo instance to make DB call
Optional<Userlicenses> ul=userlicensesRepo.findByUsernameAndUserToken(userName, userTokenEncrypted);
The application is functionally working well but over a period of 4-5 days it is creating a lot of orphan DB connections leading to memory leak. We tried setting the "release_mode", please check if we have missed anything or made a mistake in the above configuration. Appreciate your help.

Oracle db logger into Spring Boot application.properties file

I use oracle DB in Spring Boot project. I want to set error logger for the database in Spring console. This configuration must be made in application.properties file I think. (This code example shows another oracle db properties). How can I do that?
oracledb.url = <oracle_url>
oracledb.user = <oracle_user>
oracledb.password = <oracle_password>
oracledb.poolname= <oracle_poolname>
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

SpringBoot 1.5 : #SpringBootTest and memory Database

I have a SpringBoot application with spring data/jpa to connect for database.
And a propertie file yml where defined the database connection.
Everything works very well.
I create a test like that :
#ActiveProfiles("dev")
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MyMicroServiceApp.class, webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyMicroServiceAppTest {
#Test
public <T> void postConnex() {
//Create Object connexCreate
...
// Create POST
ResponseEntity<Udsaconnex> result1 = this.restTemplate().postForEntity("http://localhost:" + port + "/v1/connex",
connexCreate, Udsaconnex.class);
id = result1.getBody().getIdconnex();
assertEquals(result1.getBody().toString().isEmpty(), false);
}
}
For my test, i have not configured properties for database connection but the test work and i view in console that :
Hibernate: drop table connex if exists
I don't understand why, #SpringBootTest mock database like #DataJpaTest automatically ??
It's possible but i don't find anything about that in spring boot documentation.
Thanks for your help.
If you have application.yml file specifying DB location, then SpringBootTest will obviously use the same configuration and will use your configured DB.
From the title of your question I guess you have an in-memory database in your build dependencies. Spring-boot has some autoconfiguration for certain database (H2, HSQL, Derby) if they are found on the classpath. See this link for a list of the supported databases:
Spring Boot Embedded Database Support

How to load data with data.sql using JHipster and Spring Boot

I have a Jhipster monolithic application. I removed Liquibase and I want to use data.sql file to insert initial data. I created a data.sql and data-h2.sql which contain insert scripts. They are located under src/main/resources. But none of the data seems to be inserted.
How can I use data.sql to insert data during startup, without using Liquibase?
Commenting spring.datasource.type property and adding spring.jpa.hibernate.create-drop property helped resolve this issue. I think some jhipster configuration overrides default spring-boot configuration.
Here is how I come up with this solution:
While debugging DataSourceInitializedPublisher.publishEventIfRequired, I saw that following line returned a null reference:
private void publishEventIfRequired(EntityManagerFactory entityManagerFactory) {
DataSource dataSource = findDataSource(entityManagerFactory);
...
}
I commented spring.datasource.type property in application-dev.yml. In this way, spring switched to tomcat connection pool automatically.
Then, I found out that DataSourceInitializedPublisher.isInitializingDatabase required spring.jpa.hibernate.hbm2ddl.auto property to be defined in configuration:
private boolean isInitializingDatabase(DataSource dataSource) {
...
if (hibernate.containsKey("hibernate.hbm2ddl.auto")) {
return true;
}
return false;
}
After adding the missing property, spring-boot started to execute data.sql file.
Update
For those who want to execute a platform specific data.sql file, such as data-h2.sql, you should also add following property:
spring.datasource.platform=h2
Update
For those who need to convert default Jhipster data stored in csv files into sql format, you may refer to following gist:
https://gist.github.com/hkarakose/cf7f1b5b241dad611ba01c0211f42108

How to disable H2's DATABASE_TO_UPPER in Spring Boot, without explicit connection URL

I'm aware that H2 has a boolean property/setting called DATABASE_TO_UPPER, which you can set at least in the connection URL, as in: ;DATABASE_TO_UPPER=false
I’d like to set this to false, but in my Spring Boot app, I don’t explicitly have a H2 connection URL anywhere. Implicitly there sure is a connection URL though, as I can see in the logs:
o.s.j.d.e.EmbeddedDatabaseFactory: Shutting down embedded database:
url='jdbc:h2:mem:2fb4805b-f927-49b3-a786-2a2cac440f44;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false'
So the question is, what's the easiest way to tell H2 to disable DATABASE_TO_UPPER in this scenario? Can I do it in code when creating the H2 datasource with EmbeddedDatabaseBuilder (see below)? Or in application properties maybe?
This is how the H2 database is explicitly initialised in code:
#Configuration
#EnableTransactionManagement
public class DataSourceConfig {
#Bean
public DataSource devDataSource() {
return new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.setType(EmbeddedDatabaseType.H2)
.setScriptEncoding("UTF-8")
.ignoreFailedDrops(true)
.addScripts("db/init.sql", "db/schema.sql", "db/test_data.sql")
.build();
}
}
Also, I'm telling JPA/Hibernate not to auto-generate embedded database (without this there was an issue that two in-memory databases were launched):
spring.jpa.generate-ddl=false
spring.jpa.hibernate.ddl-auto=none
You can't w\ the generateUniqueName, but if you call setName("testdb;DATABASE_TO_UPPER=false") you can add parameters. I doubt this is officially supported, but it worked for me.
The spring code that generates the connection url is like this:
String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false", databaseName)
You may want abandon using explicit creation via EmbeddedDatabaseBuilder. Spring Boot creates H2 instance automatically based on configuration. So I would try this in application.properties:
spring.datasource.url=jdbc:h2:file:~/testdb;DATABASE_TO_UPPER=false

Resources