Data Access With Spring Boot

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 11

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

 By default, Spring Boot uses HikariCP as the database connection pool.


 Spring Boot supports JNDI connections if we are deploying our app in an application container. We can set the JNDI name in the
application.properties file.
spring.datasource.jndi-name=java:jdbc/customers
JDBC with Spring Boot example
 Go to Spring Initializer (https://start.spring.io), fill all the fields and add Web, JDBC, 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.jdbc.model;

public class Book {

public Book(Long id, String name, Double price){


this.id = id;
this.name = name;
this.price = price;
}
private Long id;
private String name;
private Double price;

//Generate setter getters


}
 Create a Repository class by using @Repository annotation.
package com.atcs.jdbc.repository;

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());
}

public Integer update(Book book) {


return jdbcTemplate.update("update books set name= ?, price=? where id = ? ", book.getName(), book.getPrice(), book.getId());
}

public Integer deleteById(Integer id) {


return jdbcTemplate.update("delete from books where id = ? ", id);
}
public List<Book> findAll() {
return jdbcTemplate.query("select * from books", (rs, rowNum) -> new Book(rs.getLong("id"), rs.getString("name"), rs.getDouble("price")));
}
}
 Implements CommandLineRunner in SpringBootApplication and override run methods and perform DB operations.
@SpringBootApplication
public class SpringBootJdbcApplication implements CommandLineRunner {

@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() {
}

public Book(String name, Double price) {


this.name = name;
this.price = price;
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private Double price;

// generate setters and getters


}
 Create BookRepository interface by extending CrudRepository interface.
public interface BookRepository extends CrudRepository<Book, Long> {
List<Book> findByName(String name);
}

 Implements CommandLineRunner in SpringBootApplication and override run methods and perform DB operations.
@SpringBootApplication
public class SpringBootJpaApplication implements CommandLineRunner {

@Autowired
private BookRepository repository;

public static void main(String[] args) {


SpringApplication.run(SpringBootJpaApplication.class, args);
}

@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());
}

String name = repository.findByName("Angular").get(0).getName();


System.out.println(name);
}
}
Thank You

You might also like