SpringBoot JDBC H2 Caching
SpringBoot JDBC H2 Caching
In Spring Boot JDBC, the database related beans such as DataSource, JdbcTemplate… auto-
configures and created during the startup.
The default connection pool in Spring Boot2 is HikariCP. It provides enterprise-ready features
and better performance. HikariCP is a JDBC DataSource implementation that provides a
connection pooling mechanism.
• If the HikariCP is present in the classpath, the Spring Boot automatically configures it.
• If the HikariCP is not found in the classpath, Spring Boot looks for the Tomcat JDBC
Connection Pool. If it is on the classpath Spring Boot, pick it up.
• If both the above options are not available, Spring Boot chooses Apache Commons DBCP2 as
the JDBC connection pool.
2
C2 - Restricted
SPRING BOOT JDBC – MAVEN STARTER AND
DEPENDENCY
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</ artifactId >
<exclusions>
<exclusion>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</ artifactId >
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>9.0.10</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.9</version>
<socpe>runtime</scoope>
</dependency>
3
C2 - Restricted
SPRING BOOT JDBC - EXAMPLE
create database springbootdb
create table user(id int primary key not null auto_increment, name varchar(100), email varch
ar(100));
// create application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb
spring.datasource.username=root
spring.datasource.password=mysql
spring.jpa.hibernate.ddl-auto=create-drop
5 Nom de la présentation
C2 - Restricted
SPRING BOOT H2 DB
*Réussir la transformation. Ensemble.
Use of in-memory database is when we do not need to persist the data. The in-memory databases are
volatile, by default, and all stored data lost application is restarted.
H2 DB Maven dependency –
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
application.properties file with DB URL and credentials:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
• in the spring.datasource.url property, mem is the name of an in-memory database
7
C2 - Restricted and testdb is the name of the schema
SPRING BOOT H2 DB – PERSIST DATA
Persist(save of disc) the data in H2 Database - to persist the data in the H2 database, we should store
data in a file. To achieve the same, we need to change the datasource URL property.
#to persist the data on Disc
spring.datasource.url=jdbc:h2:file:/data/sampledata
spring.datasource.url=jdbc:h2:C:/data/sampledata
For H2 database, we can enable the console (http://localhost:8080/h2-console) by using the following
property.
#enabling the H2 console
spring.h2.console.enabled=true
import org.springframework.data.repository.CrudRepository;
import com.javatpoint.model.Student;
public interface StudentRepository extends CrudRepository<Student, Integer> {
/***/
}
8
C2 - Restricted
SPRING BOOT H2 DB – CRUD OPERATION
Service class - StudentService.java
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.javatpoint.model.Student;
import com.javatpoint.repository.StudentRepository;
@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;
//getting all student records
public List<Student> getAllStudent() {
List<Student> students = new ArrayList<Student>();
studentRepository.findAll().forEach(student -> students.add(student));
return students;
}
//getting a specific record
public Student getStudentById(int id) {
return studentRepository.findById(id).get();
}
public void saveOrUpdate(Student student) {
studentRepository.save(student);
}
//deleting a specific record
public void delete(int id) {
studentRepository.deleteById(id);
}
}
9
C2 - Restricted
Delivering Transformation. Together.
10 Nom de la présentation
C2 - Restricted
SPRING BOOT CACHING
*Réussir la transformation. Ensemble.
The cache abstraction mechanism applies to Java methods. The main objective of using cache abstraction
is to reduce the number of executions based on the information present in the cache. It applies to
expensive methods such as CPU/IO bound
Every time, when a method invokes, the abstraction applies a cache behavior to the method. It checks
whether the method has already been executed for the given argument or not .
If yes, the cached result is returned without executing the actual method.
If no, first, the method executes, and the result is cached and returned to the user.
• The developers take care of two things while working with cache abstractions.
Cache Declaration: It identifies the methods that need to be cached.
Cache Configuration: The backing cache where the data is stored and read from.
@Caching - It is used when we need both annotations @CachePut or @CacheEvict at the same time on
the same method.
In the following example, we have used the annotation @Caching and grouped all the @CacheEvict
annotations.
@Caching(evict = {@CacheEvict("phone_number"), @CacheEvict(value="directory",
key="#student.id") })
public String getAddress(Student student)
{ //some code }
@Cacheable - It is a method level annotation. It defines a cache for a method's return value. In the below
example, we have cached the return value of the method studentInfo() in cacheStudentInfo, and id is the
13
unique key that identifies each entry in the cache.
C2 - Restricted @Cacheable(value="cacheStudentInfo", key="#id")
SPRING BOOT CACHING
Conditional caching - method will be cached if the argument name has a length shorter than 20.
@Cacheable(value="student", condition="#name.length<20")
public Student findStudent(String name)
{ //some code }
@CacheEvict - It is a method level annotation. It is used when we want to remove stale or unused data from
the cache.
Evict the whole cache:
@CacheEvict(allEntries=true)
@Cacheable annotation skips the method execution while the @CachePut annotation runs the method and put
the result into the cache.
The following method will update the cache itself.
@CachePut(cacheNames="employee", key="#id") //updating cache
public Employee updateEmp(ID id, EmployeeData data)
{ //some code
}
14
C2 - Restricted
SPRING BOOT CACHING - EXAMPLE
Spring Boot Cache Dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
//enabling caching
@EnableCaching
public class SpringBootCacheExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCacheExampleApplication.class, args);
}
}
15
C2 - Restricted
SPRING BOOT CACHING - EXAMPLE
import java.util.Arrays;
import java.util.List;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.javatpoint.model.Customer;
@RestController
public class CustomerController {
@RequestMapping("/customerinfo")
//defines a cache for method's return value
@Cacheable(value="customerInfo")
public List customerInformation(){
System.out.println("customer information from cache");
//adding customer detail in the List
List detail=Arrays.asList(new Customer(“James Smith"));
return detail;
}
}
16
C2 - Restricted
Delivering Transformation. Together.
17 Nom de la présentation
C2 - Restricted
UPLOAD & DOWNLOAD USING SB
REST API
*Réussir la transformation. Ensemble.
19
C2 - Restricted