- Prerequisite
- What is Spring Data?
- Started with Spring Initializr
- Add Dependencies
- Define an Entity
- Create Simple Queries
- Create an Application Class
- Execute Application and Check Result
Prerequisite
- IDE (Integrated development environment)
- JDK 8 or later
- Maven 3.2+
What is Spring Data JPA?
Spring Data JPA provides repository support for the Java Persistence API (JPA). It eases development of applications that need to access JPA data sources.
Started with Spring Initializr
Add Dependencies
- Add JPA and H2 dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
- H2 is a relational database management system
Define a Entity
Create Customer.java in src/main/java/com/example/jpa
- annotated as a JPA entity
package com.example.jpa;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
protected Customer() {}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
Customer class have 3 attributes: id, firstName, and lastName.
@Entity: JPA entity
Create Simple Queries
Spring Data JPA: By JPA, save data to Relational DataBase
Create CustomerRepository.java in src/main/java/com/example/jpa/CustomerRepository.java
package com.example.jpa;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, Long> {
List<Customer> findByLastName(String lastName);
Customer findById(long id);
}
By extending CustomerRepository and CrudRepository Customer, you will get methods (saving, deleting, and finding).
And Spring Data JPA: you can define query method. For example, CustomerRepository includes findByLastName() method.
General Java Application do not have to write an implementation of repository interface. JPA will create when Application is running.
Create an Application Class
Edit JpaApplication.java in src/main/java/com/example/jpa
package com.example.jpa;
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;
@SpringBootApplication
public class JpaApplication {
private static final Logger log = LoggerFactory.getLogger(JpaApplication.class);
public static void main(String[] args) {
SpringApplication.run(JpaApplication.class);
}
@Bean
public CommandLineRunner demo(CustomerRepository repository) {
return (args) -> {
// save a few customers
repository.save(new Customer("Jack", "Bauer"));
repository.save(new Customer("Chloe", "O'Brian"));
repository.save(new Customer("Kim", "Bauer"));
repository.save(new Customer("David", "Palmer"));
repository.save(new Customer("Michelle", "Dessler"));
// fetch all customers
log.info("Customers found with findAll():");
log.info("-------------------------------");
for (Customer customer : repository.findAll()) {
log.info(customer.toString());
}
log.info("");
// fetch an individual customer by ID
Customer customer = repository.findById(1L);
log.info("Customer found with findById(1L):");
log.info("--------------------------------");
log.info(customer.toString());
log.info("");
// fetch customers by last name
log.info("Customer found with findByLastName('Bauer'):");
log.info("--------------------------------------------");
repository.findByLastName("Bauer").forEach(bauer -> {
log.info(bauer.toString());
});
// for (Customer bauer : repository.findByLastName("Bauer")) {
// log.info(bauer.toString());
// }
log.info("");
};
}
}
Main() method: Using SpringApplication.run() method, execute the application.
Execute Application and Check Result
In root directory.
$ mvn package
$ java -jar target/board-0.0.1-SNAPSHOT.jar
Check result
== Customers found with findAll():
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=2, firstName='Chloe', lastName='O'Brian']
Customer[id=3, firstName='Kim', lastName='Bauer']
Customer[id=4, firstName='David', lastName='Palmer']
Customer[id=5, firstName='Michelle', lastName='Dessler']
== Customer found with findById(1L):
Customer[id=1, firstName='Jack', lastName='Bauer']
== Customer found with findByLastName('Bauer'):
Customer[id=1, firstName='Jack', lastName='Bauer']
Customer[id=3, firstName='Kim', lastName='Bauer']