Spring Boot Data JPA tutorial
Spring Boot Data JPA
helps Java based applications access backend repository like in-memory DB, Oracle DB, MongoDB, LDAP,
etc. and perform CRUD
operations. It provides boilerplate code so that developers can focus on business logic.
JPA (Java Persistence API)
provides specification for object/relational mapping to manage relational data. Hibernate is one of the implementations of JPA. Spring Boot by default comes with H2
in-memory DB which will be used in this tutorial.
This tutorial shows how to use Spring Boot Data JPA to access a repository of Celebrities.
Step 1) Add below dependencies to pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-data-jpa</artifactId></dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId></dependency>
Step 2) Create Celebrity POJO class
Celebrity class is annotated as @Entity
which means it will be used to persist the data in DB. The JPA specification specifies that @Entity
annotation should be used for POJO class that will be used as entity class. @Id
annotation is used as primay key and to identify a Celebrity row in the DB.
import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entitypublic class Celebrity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; public Celebrity() { } public Celebrity(Long id) { this.id = id; } public Celebrity(String name) { this.name = name; } public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + "]"; }}
Step 3) Create CelebrityRepository, CelebrityService classes
CelebrityRepository interface extends CrudRepository
which provides CRUD operations for the entity (Celebrity) by default. You can add more methods to query the repository like findByName, findById. The Spring Data repository will generate query by striping the prefixes like find…By, read…By, and get…By from the method name and use rest of the method name to generate the query.
import java.util.List;import org.springframework.data.repository.CrudRepository; public interface CelebrityRepository extends CrudRepository<Celebrity, Long> { List<Celebrity> findByName(String name); Celebrity findById(long id);}
import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; @Servicepublic class CelebrityService { @Autowired private CelebrityRepository customerRepository; public void save(Celebrity customer) { customerRepository.save(customer); } public Celebrity findById(long id) { return customerRepository.findById(id); } public List<Celebrity> findAll() { return (List<Celebrity>) customerRepository.findAll(); } List<Celebrity> findByName(String name) { return (List<Celebrity>) customerRepository.findByName(name); } }
Step 4) Write SpringBootDataJPAApplication class
On startup ,SpringBootDataJPAApplication will call CelebrityService methods to save few records and then queries the records.
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean; @SpringBootApplicationpublic class SpringBootDataJPAApplication { private static final Logger log = LoggerFactory.getLogger(SpringBootDataJPAApplication.class); public static void main(String[] args) { SpringApplication.run(SpringBootDataJPAApplication.class, args); } @Bean public CommandLineRunner demo(CelebrityService service) { return (args) -> { log.info("saving customers"); service.save(new Celebrity("John Wick")); service.save(new Celebrity("Bob Dylan")); log.info("Customers found with findAll():"); for (Celebrity customer : service.findAll()) { log.info(customer.toString()); } // fetch an individual by ID Celebrity customer = service.findById(1L); log.info("Customer found with findById(1L):"); log.info(customer.toString()); service.findByName("John Wick").forEach(john -> { log.info(john.toString()); }); }; }}
Step 5) Run SpringBootDataJPAApplication
Console Output :
2021-12-20 14:49:56.592 INFO 6152 --- [main] data.SpringBootDataJPAApplication:Started SpringBootDataJPAApplication in 4.625 seconds (JVM running for 5.377)2021-12-20 14:49:56.607 INFO 6152 --- [main] data.SpringBootDataJPAApplication:saving customers2021-12-20 14:49:56.659 INFO 6152 --- [main] data.SpringBootDataJPAApplication:Customers found with findAll():2021-12-20 14:49:56.691 INFO 6152 --- [main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory2021-12-20 14:49:56.850 INFO 6152 --- [main] data.SpringBootDataJPAApplication:Customer [id=1, name=John Wick]2021-12-20 14:49:56.850 INFO 6152 --- [main] data.SpringBootDataJPAApplication:Customer [id=2, name=Bob Dylan]2021-12-20 14:49:56.866 INFO 6152 --- [main] data.SpringBootDataJPAApplication:Customer found with findById(1L):2021-12-20 14:49:56.866 INFO 6152 --- [main] data.SpringBootDataJPAApplication:Customer [id=1, name=John Wick]2021-12-20 14:49:56.897 INFO 6152 --- [main] data.SpringBootDataJPAApplication:Customer [id=1, name=John Wick]