Caused by: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName - java

My spring boot test is throwing the below error during maven build.
"level":"ERROR","logger":"com.zaxxer.hikari.HikariConfig","msg":"HikariPool-1 - jdbcUrl is required with driverClassName."
Stacktrace:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'schedulerFactoryBean' defined in class path resource
[com/pit/SchedulerConfig.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: jdbcUrl is requir
ed with driverClassName.
Caused by: java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
The method that throws an error in my MyApplicationTest.java
#SpringBootTest
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
#EnableConfigurationProperties(value = MyConfig.class)
class MyApplicationTest {
#Test
void contextLoads() {
assertNotNull(myController);
}
}
My pom has these dependencies in classpath.
spring-boot-starter-web
spring-boot-starter-test
spring-integration-sftp
postgresql
junit
quartz-scheduler
My Datasource bean is configured as below
#Configuration
public class MyDataSourceCfg {
private DataSource appDataSource() {
return DataSourceBuilder.create()
.driverClassName("org.postgresql.Driver")
.url(env.getProperty("url") // values are set from Environment
.username(env.getProperty("user"))
.password(env.getProperty("password")
.build();
}
}
Please tell me what is happening and how I avoid this error. I read about configuring Datasource in different way in case you have multiple database but I just have one postgres database. Please share your thoughts.

Considering that you have all relevant dependencies.
as Connect to PostgreSQL Database with Spring Data JPA such as :-
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
and in application.properties file:
spring.datasource.url=jdbc:postgresql://localhost:5432/dev
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQL81Dialect
With SpringBoot's powerful autoconfiguration, you don't need to explicitly create a DataSource bean and if in case you want, use these properties values.

Related

Unable to open JDBC Connection oracle and spring boot

Hello i m using oracle database but i get some errors , with spring boot :
the erors is :
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]:
Invocation of init method failed; nested exception is
javax.persistence.PersistenceException: [PersistenceUnit: default]
Unable to build Hibernate SessionFactory; nested exception is
org.hibernate.exception.JDBCConnectionException: Unable to open JDBC
Connection for DDL execution
my application properties is :
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.datasource.url= jdbc:oracle:thin:#localhost:1521:XE
spring.datasource.username=Sys
spring.datasource.password=admin
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.jpa.hibernate.ddl-auto=create
server.port = 8080
spring.jpa.show-sql=true
spring.servlet.multipart.max-file-size=-1
Which Java version you are using? Can you check if you have added dependencies in your build file?
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
Reference Link : https://www.baeldung.com/java-9-jaxbexception

Spring boot 2 (spring batch app) fails to start. Fails with BeanCreationException: Error creating bean with name 'h2Console'

I am trying to run a Spring Batch app that reads data from a SQL Server DB and writes to a csv file. Below is the DatabaseConfiguration file for the SQL Server DB:-
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
basePackages = {"com.sample.repository"},
entityManagerFactoryRef = "sampleEntityManagerFactory",
transactionManagerRef = "transManager"
)
public class CompensationConfiguration
{
#Primary
#Bean(name="cmpnDS")
#ConfigurationProperties(prefix = "sample.datasource.compensation")
public DataSource sampleDataSource() {
return DataSourceBuilder.create().build();
}
#Primary
#Bean(name = "sampleEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean sampleEntityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("cmpnDS") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.opencodez.entity")
.build();
}
#Primary
#Bean(name = "transManager")
public PlatformTransactionManager hrprdTransactionManager(#Qualifier("sampleEntityManagerFactory")
EntityManagerFactory entityManagerFactoryBean) {
return new JpaTransactionManager(entityManagerFactoryBean);
}
}
Following is a snippet from the pom file:-
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>mybat</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybat</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven-jar-plugin.version>2.6</maven-jar-plugin.version>
<spring-cloud.version>Hoxton.RC2</spring-cloud.version>
</properties>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
and the following in the properties file:-
spring:
datasource:
url: jdbc:h2:mem:testdb
username: sa
password:
driver-class-name: org.h2.Driver
When I try to launch the app it is failing to start with the below error:-
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'h2Console' defined in class path resource [org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.web.servlet.ServletRegistrationBean]: Factory method 'h2Console' threw exception; nested exception is java.lang.IllegalArgumentException: dataSource or dataSourceClassName or jdbcUrl is required.
This app reads a SQL Server DB for processing records. The spring batch uses in memory DB H2Database. Is this a multi-datasource scenario? I didn't do any coding for the datasource configuration of H2 as it should be autoconfigured. I have all the required dependencies included in the pom - sprign-batch-core, devtools, h2 database, jpa etc.
I got around this by setting
spring.h2.console.enabled=false
in my spring boot application.properties file.
The doc for that property says that you could get rid of this by instead removing the pom dependency for spring-boot-devtools (detailed here).
You have to delete h2's related jar files in .m2 maven local repository, It's must be corrupted.
After that, you have to run "mvn spring-boot:run" again, Maybe more that one jar was corrupted so check it and reapet recipe (every time you need to run that command after delete that jar).
I created two Datasource Configuration classes, one for each database, and marked the h2 datasource as primary. The app started fine after this change.

Use in-memory db to write tests for Rest controllers

I'm writing a test for a Spring boot Rest controller. This rest controller writes some values to the db.
I want to use in-memory database which Spring provides for this test. According to this doc I have to annotate the test class with #DataJpaTest, which causes this error:
java.lang.IllegalStateException: Failed to load ApplicationContext
Further down in the error stack trace I see the following exception was thrown:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of #AutoconfigureTestDatabase.
This is the test class which I'm working on:
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
#DataJpaTest
public class AuthenticationControllerFTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private AuthenticationManager authenticationManager;
#Autowired
private WebApplicationContext context;
#Autowired
private Filter springSecurityFilterChain;
#Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.addFilters(springSecurityFilterChain).build();
}
#Test
public void testCreate() throws Exception {
String exampleUserInfo = "{\"name\":\"Salam12333\",\"username\":\"test#test1.com\",\"password\":\"Salam12345\"}";
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/signup")
.accept(MediaType.APPLICATION_JSON).content(exampleUserInfo)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
int status = response.getStatus();
Assert.assertEquals("http response status is wrong", 200, status);
}
}
What is causing this error ?
Edit 1
This is the content of my application.properties:
spring.datasource.username = hello
spring.datasource.password = hello
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/myproject?useSSL=false
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
logging.level.org.springframework.web=DEBUG
server.port = 8443
server.ssl.key-store = classpath:tomcat.keystore
server.ssl.key-store-password = hello
server.ssl.key-password = hello
server.ssl.enabled = true
server.ssl.key-alias=myproject
Edit 2
I added the following to my pom.xml:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
I created application-test.properties with the following content:
spring.datasource.username= root
spring.datasource.password= password
spring.datasource.driver-class-name= org.h2.Driver
spring.datasource.url= jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
What is the username and passowrd ? Where should I set them ?
I also added #ActiveProfiles("test") to the test class, when I run the test I get an error which includes this line :
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Assuming you annotate class with #SpringBootApplication, which enables auto-configuration and you have H2 dependency on classpath(see below) Spring Boot will see H2 in-memory database dependency and it will create javax.sql.DataSource implementation. Default connection URL is jdbc:h2:mem:testdb and the default username and password are: username: sa and password: empty.
application.properties file
spring.datasource.url=jdbc:h2:mem:tesdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
spring.jpa.show-sql = true
spring.h2.console.enabled=true // if you need console
H2 Dependency
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency> // If you need h2 web console
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
You can gain access to h2 console for management http://localhost:8080/h2-console
For Testing REST service with in-memory DB, you need to following things:
1. Add h2 dependency in pom.xml
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
2. Define h2 configuration in application.properties or application.yaml
spring.jpa.database = h2
spring.datasource.url=jdbc:hsqldb:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.HSQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
3. Annotate you test class
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
Complete code will be like:
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AuthenticationControllerFTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private AuthenticationManager authenticationManager;
#Autowired
private WebApplicationContext context;
#Autowired
private Filter springSecurityFilterChain;
#Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.addFilters(springSecurityFilterChain).build();
}
#Test
public void testCreate() throws Exception {
String exampleUserInfo = "{\"name\":\"Salam12333\",\"username\":\"test#test1.com\",\"password\":\"Salam12345\"}";
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/signup")
.accept(MediaType.APPLICATION_JSON).content(exampleUserInfo)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
int status = response.getStatus();
Assert.assertEquals("http response status is wrong", 200, status);
}
}
Remove both annotations #AutoConfigureMockMvc and #DataJpaTest. You are trying to test the complete applciation, so need the #SpringBootTest annotation. #DataJpaTest is only needed if you want to test only the data apllication slice. Have a look at this: https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4
In spring boot we do not require to add any thing additional for in memory database configuration except for jar file on class path and application property file (application.properties) on the class path (src/test/resources if maven is used) rest of the things will be taken care by spring boot (beauty of boot).
Another option is to provide profile specific properties file on the class path src/amin/resources (for example application-test.properties)
Both of the file are valid for test configurations
Sample configuration for property file is given below (consider HSQL DB jar on class path):
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.database = HSQL
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect
spring.datasource.driverClassName = org.hsqldb.jdbcDriver
spring.datasource.url: jdbc:hsqldb:mem:scratchdb
spring.datasource.username = sa
spring.datasource.password = pass
Maybe this helps.
spring.datasource.url=jdbc:hsqldb:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.HSQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
See also Configure specific in memory database for testing purpose in Spring
I believe, you can use below in-memory db with integration test -
This will also help if you are using json[b](though it is in DB2 but some ops like inserting/updating not support with our code) datatype or any other field that is not present in DB2 (compatibility issue).
Then refer this TestContainer - Stackoverflow answer
Pom.xml
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.15.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.15.1</version>
<scope>test</scope>
</dependency>
XyzIT.java
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#ActiveProfiles("test")
#Testcontainers
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
#Test
void test(){
var mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/opportunities/process")
.header("emailId", "ravi.parekh#xyz.com")
.header("Authorization", "authorization")
.header("Content-Type", "application/json").content(objectMapper.writeValueAsString(opportunity))).andReturn();
}
Application-test.yml
datasource:
initialization-mode: always
schema: classpath*:schema-h2.sql #initial sql script to createDB
url: jdbc:tc:postgresql:11.9:///
jpa:
hibernate.ddl-auto: none
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
format_sql: true
default_schema: public
show-sql: true

Spring Boot and Tomcat not finding JNDI resources

I'm using Spring Boot 1.4.2.RELEASE. I'm also using Tomcat 8.5.9 (NOT embedded) and Java 8.
In my application.properties file, I can manually configure my datasource using:
spring.datasource.url = jdbc:as400://blahblah....
spring.datasource.username = myuser
spring.datasource.password = password
spring.datasource.driver-class-name=com.ibm.as400.access.AS400JDBCDriver
This works just fine. But, we use Tomcat to host our connections. In Tomcat, we have:
<GlobalNamingResources>
<Resource name="jdbc/BLAH" ..... />
</GlobalNamingResources>
So I then changed application.properties to:
spring.datasource.jndi-name=java:comp/env/jdbc/BLAH
spring.jpa.database-platform=org.hibernate.dialect.DB2400Dialect
spring.jpa.show-sql=true
Now, I can't even build the application. I get the following exception:
o.s.w.c.s.GenericWebApplicationContext :
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration':
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in class path resource
[org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.class]:
Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [javax.sql.DataSource]:
Factory method 'dataSource' threw exception; nested exception is
org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException:
Failed to look up JNDI DataSource with name 'java:comp/env/jdbc/BLAH';
nested exception is javax.naming.NoInitialContextException:
Need to specify class name in environment or system property, or as an applet parameter,
or in an application resource file: java.naming.factory.initial
The NoInitialContextException leads me to believe that Spring Boot cannot find Tomcat running so it can't perform a JNDI lookup.
Keep in mind, the exact same setup worked for us using Spring Boot 1.2.5.RELEASE. We have another app that uses 1.2.5.RELEASE, Java 7 and Tomcat 7 and it works using JNDI resources. But using the newest Spring Boot, Java 8 and Tomcat 8 doesn't.
Any help is appreciated.
Some snippets from my pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath/>
</parent>
...
<dependencies>
<dependency>
<groupId>net.sf.jt400</groupId>
<artifactId>jt400</artifactId>
<version>6.7</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
....
</dependencies>
Other code snippets:
#SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
#SpringBootConfiguration
#EnableAutoConfiguration
#ComponentScan(basePackages = "com.company.myapp")
#EnableJpaRepositories(basePackages = "com.company.myapp.repository")
#EnableTransactionManagement
#EnableVaadin
#EnableVaadinServlet
public class AppConfiguration {
}
UPDATE
I've created the resources within Tomcat (external) using the GlobalNamingResources in our server.xml.
This works for other applications.
UPDATE 2
Forgot to mention that I have the following in a src/main/webapp/META-INF/context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<ResourceLink global="jdbc/BLAH"
name="jdbc/BLAH"
type="com.mchange.v2.c3p0.ComboPooledDataSource"/>
</Context>
UPDATE 3
Also, I want to make it clear the problem happens during the maven package step.
If you are deploying on a standalone Tomcat (Not embedded), I'm fairly sure you need to define your JNDI resources on the Tomcat and not in application.properties, but in server.xml like this:
<GlobalNamingResources>
<Resource name="jdbc/serverdb" auth="Container" type="javax.sql.DataSource"
maxTotal="5" maxIdle="5" maxWaitMillis="30000"
validationQuery="select 1" testOnBorrow="true"
username="$AUTH_DB_USER" password="$AUTH_DB_PASSWORD" driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://$AUTH_DB_HOST:5432/$AUTH_DB_NAME"/>
</GlobalNamingResources>

Spring Boot - Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration'

I have spring boot application setup. Now I need to add Spring JDBC Template to it. While doing this, I am facing below exception.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'XXX': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.jdbc.core.JdbcTemplate com..XXX.jdbcTemplate; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$JdbcTemplateConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "LOCAL" are currently active).
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (the profiles "LOCAL" are currently active).
Below is the code.
#Service
public class XXX {
#Autowired
JdbcTemplate jdbcTemplate;
public void testDataSource() {
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from C_MASTER");
System.out.println("list : " + list);
}
}
Java Config
#Configuration
#ComponentScan
#EnableTransactionManagement
public class DAODataServiceManagerConfiguration {
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
dataSource.setUrl("jdbc:oracle:thin:#g9u1769.houston.hpecorp.net:1525:ODSDBD");
dataSource.setUsername("Solid_batch");
dataSource.setPassword("solid_batch123");
return dataSource;
}
}
As spring boot looks for application.properties, I have added that too in the resources directory.
appliation.properties.
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#g9u1769.houston.hpecorp.net:1525:ODSDBD
spring.datasource.username=Solid_batch
spring.datasource.password=solid_batch123
spring.datasource.initialize=true
It is unable to build the application. Correct me if I am doing anything wrong.
You are missing ojdbc jar in your project classpath, follow below steps to download, install and use it as a dependency:
Download ojdbc6.jar from here.
Install it, running command -
mvn install:install-file -Dfile={Path/to/your/ojdbc.jar} -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0 -Dpackaging=jar
For jar version, extract the jar file and check the Implementation-Version in MANIFEST.MF, for instance:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.6.5
Created-By: 1.5.0_51-b10 (Sun Microsystems Inc.)
Implementation-Vendor: Oracle Corporation
Implementation-Title: JDBC
Implementation-Version: 11.2.0.4.0
Repository-Id: JAVAVM_11.2.0.4.0_LINUX.X64_RELEASE
Specification-Vendor: Sun Microsystems Inc.
Specification-Title: JDBC
Specification-Version: 4.0
Main-Class: oracle.jdbc.OracleDriver
sealed: true
Name: oracle/sql/converter/
Sealed: false
Name: oracle/sql/
Sealed: false
Name: oracle/sql/converter_xcharset/
Sealed: false
Name: oracle/replay/driver/
Sealed: false
Add as a dependency in the project, as follows:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0</version>
</dependency>
Use jdbctemplate by extends JdbcDaoSupport .
By it programmer not concern about the open and close the connection.
Use commons-dbcp2-2.1.1.jar and commons-pool2-2.4.2.jar for use dbcp2 because dbcp2 support Connection pooling.
It's a technique to allow multiple clinets to make use of a cached set of shared and reusable connection objects providing access to a database
public class XXX extends JdbcDaoSupport {
public void testDataSource() {
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from C_MASTER");
System.out.println("list : " + list);
}
}
In spring.xml write
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/database_name" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<bean id="xXX" class="your_package_name.XXX">
<property name="dataSource" ref="dataSource" />
</bean>
I have gone through spring boot reference document. I came to know that if we are using (H2, HSQL or Derby) databases then we don't require application.properties.
If the project is having Oracle database, then application.properties should be updated. In my case I have updated the properties file.
So I have updated only following things, then it worked properly.
pom.xml
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
configuration file
#Configuration
public class DaoConfig {
#Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("oracle.jdbc.OracleDriver");
dataSource.setUrl("xxx");
dataSource.setUsername("xxx");
dataSource.setPassword("xxx");
return dataSource;
}
#Bean
public JdbcTemplate getJdbcTemplate() {
return new JdbcTemplate(getDataSource());
}
I hope this might help someone.
Thanks #ChrisThompson and #Arpit

Categories