You can
create a table using execute method of JdbcTemplate.
jdbcTemplate.execute("CREATE
TABLE employees (id SERIAL, first_name VARCHAR(255), last_name
VARCHAR(255))");
Step 1:
Create a maven
project ‘springJDBC’.
Step 2:
Update dependencies
in pom.xml
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springJDBC</groupId>
<artifactId>springJDBC</artifactId>
<version>1</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
</project>
Step 3:
Define an Employee
entity class.
package com.sample.app.entity;
public class Employee {
private int id;
private String firstName;
private String lastName;
public Employee(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
.append(lastName).append("]");
return builder.toString();
}
}
Step 4:
Create
application.properties file under ‘src/main/resources’ folder and configure
data source conffigurations.
logging.level.root=WARN ## H2 specific properties spring.h2.console.enabled=true spring.h2.console.path=/h2 spring.datasource.url=jdbc:h2:file:~/db/myOrg.db;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1; spring.datasource.username=krishna spring.datasource.password=password123 spring.datasource.driverClassName=org.h2.Driver ## Database connection pooling properties # Number of ms to wait before throwing an exception if no connection is available. spring.datasource.max-wait=10000 # Maximum number of active connections that can be allocated from this pool at the same time. spring.datasource.tomcat.max-active=10 spring.datasource.tomcat.max-idle=5 spring.datasource.tomcat.min-idle=3
Step 5:
Define App.java like
below.
package com.sample.app;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import com.sample.app.entity.Employee;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SpringBootApplication
public class App {
private static final Logger log = LoggerFactory.getLogger(App.class);
@Autowired
JdbcTemplate jdbcTemplate;
public static void main(String args[]) {
SpringApplication.run(App.class, args);
}
@Bean
public CommandLineRunner demo() {
return (args) -> {
log.info("Creating tables");
jdbcTemplate.execute("DROP TABLE employees IF EXISTS");
jdbcTemplate
.execute("CREATE TABLE employees(" + "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");
jdbcTemplate
.execute("INSERT INTO employees(id, first_name, last_name) VALUES (1, 'Rama Krishna', 'Gurram')");
System.out.println("Printing Employees\n");
jdbcTemplate.query(
"SELECT id, first_name, last_name FROM employees",
(rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"),
rs.getString("last_name"))
).forEach(customer -> System.out.println(customer));
};
}
}
'execute'
method of JdbcTemplate is used to execute SQL queries.
Example
jdbcTemplate.execute("DROP
TABLE employees IF EXISTS");
jdbcTemplate.execute("CREATE
TABLE employees(" + "id SERIAL, first_name VARCHAR(255), last_name
VARCHAR(255))");
jdbcTemplate.execute("INSERT
INTO employees(id, first_name, last_name) VALUES (1, 'Rama Krishna',
'Gurram')");
'query'
method is used to extract the information from given tables.
Example
List<Employee>
emps = jdbcTemplate.query("SELECT id, first_name, last_name FROM employees",
(rs, rowNum) -> new Employee(rs.getInt("id"),
rs.getString("first_name"), rs.getString("last_name")));
Total
project structure looks like below.
Run App.java, you can see
below messages in console.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.6.RELEASE)
Printing Employees
Employee [id=1, firstName=Rama Krishna, lastName=Gurram]
You can
download complete working application from this link.
No comments:
Post a Comment