SPRING BOOT DATA JPA
Java Persistence API
Introduction
Bean
Instance
An Entity
Entities
Table
Primary Key
Persistent Fields�
Entity Class
@Entity
@Table(name=“customers")
public class Customer {
@Id
@column(“custid”)
private Long custId;
@column(“customerName”)
private String customerName;
}
Primary Key Generation
Primary Key Generation
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int rollNumber;
�
Repository
�Repository�
�CrudRepository Interface�
�PagingAndSortingRepository�
CRUD Repository
Creating Spring Data Application
Entity
@Entity
@Table(name = "demo_Book")
public class Book {
@Id
@column(“bookid”)
long bookId;
@column(“authorname”)
String authorName;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@column(“dateofpublication”)
LocalDate dateOfPublication;
@column(“amount”)
double amount;
}
Using CRUD Repository
@Service
public class BookService {
@Autowired
private BookRepository repo;
public Iterable<Book> getBooks(){
return repo.findAll();
}
public Book addBook(Book book) {
return repo.save(book);
}
}
Main Method
public static void main(String[] args) {
ConfigurableApplicationContext ctx
=SpringApplication.run(UnderstandingComponentScanApplication.class, args);
BookService service= ctx.getBean(BookService.class));
service.getBooks().forEach(System.out::println);
}
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: srivatsan
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: update
H2 In memory Data Base Configuration
spring:
datasource:
url: jdbc:h2:file:C:/h2data/sample
username: sa
password:
driver-class-name: org.h2.Driver
h2:
console:
enabled: true
path: /h2
jpa:
hibernate:
ddl-auto: update
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
show-sql: true
Custom Query Methods
Query Method Syntax
Rules
Valid Method
�
Query Method Syntax
Query Method Syntax
Custom Query Method
public interface BookRepository extends CrudRepository<Book, Long> {
List<Book> findByAuthor(String author);
List<Book> findDistinctByCategory(String category);
List<Book> findByAuthorAndCategory(String author, String category);
@Query("SELECT a FROM Book a WHERE a.author=:authore and a.price>:price")
List<Book> fetchBooks(@Param("author") String author, @Param("price") double price);
}
JPQL
@Query("FROM Author WHERE firstName = ?1")
List<Author> findByFirstName(String firstName);
�
@Query
�
Custom Query Method
@Query(value = "select name,author,price from Book b where b.price>?1 and b.price<?2")
List<Book> findByPriceRange(long price1, long price2);
@Query(value = "select name,author,price from Book b where b.name = :name AND b.author=:author AND b.price=:price")
List<Book> findByNamedParam(@Param("name") String name, @Param("author") String author, @Param("price") long price);
@Query(value = "select * from Book b where b.name=?1", nativeQuery = true)
List<Book> findByName(String name); �
�Examples:�