Data Access With Spring Boot
Data Access With Spring Boot
Data Access With Spring Boot
Table Content
1. What is Spring Data
2. JDBC with Spring Boot
3. Example of JDBC with Spring Boot
4. Spring Boot JPA
5. Example of Spring Boot JPA
What is Spring Data
The Spring Data is a data-driven framework, which makes it easy to interact with databases.
It allowed us to focus on business logic by handling all the hard lifting, including handling connections (open, close, and pooling),
transactions, and the way you interact with the databases.
The following are some of the Spring Data features.
1. Powerful repository and custom object-mapping abstractions
2. Dynamic query derivation from repository method names.
3. Support for transparent auditing (created, last changed)
4. Possibility to integrate custom repository code.
It allows us to interact with both relational and non-relation databases.
JDBC with Spring Boot
Spring Boot uses auto-configuration feature to configures the datasource based on the SQL driver in classpath.
In Spring Boot JDBC, the database related beans like DataSource, JdbcTemplate and NamedParameterJdbcTemplate will be
configured and created during the startup.
For in-memory database, nothing to configure, if we want to connect to a real database, define the datasource properties in
application.properties file.
#spring.datasource.url=jdbc:mysql://192.168.1.4:3306/test
#spring.datasource.username=system
#spring.datasource.password=system@123
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
mport com.atcs.jdbc.model.Book;
@Repository
public class BookRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public Integer save(Book book) {
return jdbcTemplate.update("insert into books(name,price) values(?,?)", book.getName(), book.getPrice());
}
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private BookRepository bookRepository;
public static void main(String[] args) {
SpringApplication.run(SpringBootJdbcApplication.class, args);
}
@Override
public void run(String... args) {
createTables();
Book book1 = new Book(1l,"Spring Boot", 1000.00);
bookRepository.save(book1);
Book book2 = new Book(2l,"Spring Cloud", 2000.00);
bookRepository.save(book2);
List<Book> books = bookRepository.findAll();
for(Book book : books) {
System.out.println(book.getId() +"," + book.getName() +", "+ book.getPrice());
}
}
public void createTables() {
jdbcTemplate.execute("DROP TABLE books IF EXISTS");
jdbcTemplate.execute("CREATE TABLE books(" + "id SERIAL, name VARCHAR(255), price NUMERIC(15, 2))");
}
}
Spring Boot JPA
Spring Data JPA provides an additional level of functionality: creating repository implementations directly from interfaces and using
conventions to generate queries from method names.
One of the most important benefits from the Spring Data JPA is that we don’t need to worry about implementing basic CRUD
functionalities.
We only need to create an interface that extends from a Repository<T,ID>, CrudRepository<T,ID>, or JpaRepository<T,ID>.
The JpaRepository interface offers not only what the CrudRepository does, but also extends from the PagingAndSortingRepository
interface that provides extra functionality.
Another feature from Spring Data JPA are the query methods, which are a very powerful way to create SQL statements with the fields
of the domain entities.
Spring Boot JPA example
Go to Spring Initializer (https://start.spring.io), fill all the fields and add Web, JPA, H2, MySQL starter dependencies.
Click on Generate Project button, which downloads a ZIP file. Unzip it and import the project in Eclipse IDE.
Create a model class.
package com.atcs.jpa.model;
@Entity
public class Book {
public Book() {
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private Double price;
Implements CommandLineRunner in SpringBootApplication and override run methods and perform DB operations.
@SpringBootApplication
public class SpringBootJpaApplication implements CommandLineRunner {
@Autowired
private BookRepository repository;
@Override
public void run(String... args) {
repository.save(new Book("Spring boot", 1000.00));
repository.save(new Book("Angular", 2000.00));
List<Book> books = (List<Book>) repository.findAll();
for (Book book : books) {
System.out.println(book.getId() + "," + book.getName() + ", " + book.getPrice());
}