0% found this document useful (0 votes)
2 views

spring data with boot in details

The document outlines the use of Spring Data with Spring Boot, covering CRUD operations, derived queries, pagination, and joins. It includes code examples for creating a Book entity, a repository interface, and various query methods. Additionally, it discusses configuration settings for JPA and MySQL, as well as logging and pagination techniques for managing large datasets.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

spring data with boot in details

The document outlines the use of Spring Data with Spring Boot, covering CRUD operations, derived queries, pagination, and joins. It includes code examples for creating a Book entity, a repository interface, and various query methods. Additionally, it discusses configuration settings for JPA and MySQL, as well as logging and pagination techniques for managing large datasets.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

Spring data with spring boot:

---------------------------

1. hello world
2. CURD operation
3. turning off repo definations
4. derived quaries from method names
5. relational, logical, date related,containing checking quaries
6. JPQL data with spring data, Sort quaries result using method arguments
7. pagination
8. joins

Depdendencies: web,jpa, mysql

spring.jpa.hibernate.ddl-auto=update
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
spring.jpa.show-sql=true

spring.datasource.url= jdbc:mysql://localhost:3306/data
spring.datasource.username=root
spring.datasource.password=root

@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long bookId;
private String title;
private Date publishDate;
private int pageCount;
private double price;
}

public interface BookRepo extends JpaRepository<Book, Long> {

@SpringBootApplication
public class SpringDataApplication implements CommandLineRunner {

@Autowired
private BookRepo repo;

public static void main(String[] args) {


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

@Override
public void run(String... arg0) throws Exception {
repo.save(new Book("java is fun", new Date(), 300, 340));
repo.save(new Book("java is fun", new Date(), 300, 340));
}
}

CURD operation
-------------
-> adding records

use repository.save(books) it can be used to save book one by one and


in one go!

-> deleting records

repository.delete(1L);

repository.delete(repository.findOne(2L));

repository.delete(repository.findAll(new ArrayList<Long>(){{
add(3L);
add(4L);
}}));

repository.deleteInBatch(repository.findAll(new ArrayList<Long>(){{
add(5L);
add(6L);
}}));

repository.deleteAll();

repository.deleteAllInBatch();

-> update records

Book book repository.findOne(1L);


//...change book
book.setTitle("java in action");
repository.save(book);
System.out.println(repository.findOne(1L));

-> retriving records

List<Book> books = repository.findAll(new ArrayList<Long>(){{


add(1L);
add(3L);
add(7L);
}});

for(Book book:books){
System.out.println(book);
}
3. turning off repo definations
----------------------------------

-> lets say our requirment is to create an safe repo, only for reading
purpose

-> use @NoRepositoryBean, Spring jpa will only give implementation for
methods that are mentioned in interface!

@NoRepositoryBean
public interface ReadOnlyRepository<T,ID extends Serializable> extends
Repository<T, ID> {

T findOne(ID id);
Iterable<T> findAll();
}

4. derived quaries from method names


-----------------------------------
-> Spring Data can derived quaries based on method name declared into the
repo interface

class Person{

private firstName;

Ex:
public interface PersonRepository extends CrudRepository<Person,
String>{
public List<Person>findByFirstName(String firstName);
}

=> Quary generated:


select p from Person p where p.firstName=?

Agenda:
-------
How derived queries are constructed?

keyword used to construct specific constraints

define ordering for result sets


limit result set sizes

create constrainits that transverse nested properties

How derived queries are constructed? and hello world


-----------------------------------------------------

String comparision methods:


---------------------------

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

//Spring data inspect method sign and find findBy keyword


//query builder in background remove findBy and inspect next portion
"title" (title of POJO)
//using this infor spring data enable to construct quaries....

public Book findByTitle(String title);


}

Book book=repository.findByTitle("Java 8 in action");


System.out.println(book);

More examples:
-------------

public List<Book> findByTitle(String title);

public List<Book> findByTitleLike(String title);

public List<Book> findByTitleContaining(String title);

public List<Book> findByTitleStartingWith(String title);

public List<Book> findByTitleEndingWith(String title);

public List<Book> findByTitleIgnoreCase(String title);

testing :
---------
List<Book> books=repository.findByTitleEndingWith("action");
for(Book b: books)
System.out.println(b.getTitle());
relational comparision methods in derived quaries
----------------------------------------------------

public List<Book> findByPageCountEquals(int pageCount);

public List<Book> findByPageCountGreaterThan(int pageCount);

public List<Book> findByPageCountLessThan(int pageCount);

public List<Book> findByPageCountGreaterThanEqual(int pageCount);

public List<Book> findByPageCountLessThanEqual(int pageCount);

public List<Book> findByPageCountBetween(int min, int max);

testing:
---------

for(Book b:repository.findByPageCountBetween(160, 220)){


System.out.println(b);
}

Logical operator in derived quaries (or not and)


-------------------------------------
public List<Book> findByTitleContainingOrTitleContaining(String title, String
title2);

public List<Book> findByTitleContainingAndPageCountGreaterThan(String title,


int pageCount);

public List<Book> findByTitleNot(String title);

for(Book b:repository.findByTitleNot("Head first")){


System.out.println(b);
}
Date comparision in spring data
------------------------------

public List<Book> findByPublishDateAfter(Date date);

public List<Book> findByPublishDateBefore(Date date);

public List<Book> findByPublishDateBetween(Date date,Date date2);

Date date = new SimpleDateFormat("MM/dd/yyyy").parse("10/22/1995");


Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse("10/22/1997");
for(Book b:repository.findByPublishDateBetween(date,date2)){
System.out.println(b);
}

Quaries to check containing


------------------------------

public List<Book> findByTitleContainingOrderByTitleAsc(String title);

public List<Book> findByTitleContainingOrderByTitleDesc(String title);

public List<Book> findTopByOrderByPageCountDesc();// find top book

public List<Book> findTopByOrderByPageCountDesc();

public List<Book> findFirstByOrderByPageCountAsc();

public List<Book> findTop5ByOrderByPriceDesc(); //top 5 costly books....

for(Book b:repository.findByTitleContainingOrderByTitleDesc("a")){
System.out.println(b);
}

6. JPQL data with spring data, Sort quaries result using method arguments
--------------------------------------------------------------------------

Manually assigning an quaries @Query


-------------------------------

@Query("select b from Book b")


public List<Book> queryOne();

@Query("select b from Book b where b.pageCount > ?1")


public List<Book> queryTwo(int pageCount);
@Query("select b from Book b where b.title = :title")
public List<Book> queryThree(@Param("title") String title);

testing:
---------

for(Book b:repository.queryThree("head first")){


System.out.println(b);
}

Named Quaries
---------------

Demo:

@NamedQueries({@NamedQuery(name="Book.queryOne", query="select b from Book


b"),
@NamedQuery(name="Book.queryTwo", query="select b from Book b where
b.pageCount > ?1"),
@NamedQuery(name="Book.queryThree", query="select b from Book b where b.title
= :title")})
public class Book {

......
}

Note: Quary name Book.queryOne corrosponding to method named queryOne() of


Book class
public List<Book> queryOne();

.....

testing:
---------

for(Book b:repository.queryThree("head first")){


System.out.println(b);
}

7. pagination (sub set of large set)


--------------

=> Pagination is imp tech for large result set to displayed to a web page
=> breading down larger data set to sub set... pagination
=> serch engine

Spring provide paging and sorting repo out of the box....contain several
method to support pagination

Hello World:
to see record of page one (0 for first page) and three records
to see record of page two (1 for first page) and three records

for(Book b:repository.findByPageCountGreaterThan(150, new PageRequest(0,3))){


System.out.println(b);
}

ex:
for(Book b:repository.findAll(new PageRequest(0,3))){
System.out.println(b);
}

Or we can defind an new method in repo:


---------------------------------------
@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

public List<Book> findByPageCountGreaterThan(int pageCount, Pageable


pageable);
}

Sorting records:
----------------
Sorting using Spring JPA is very easy:

Getting book sorted as per pageCount


----------------------------------
for(Book b:repository.findAll(new Sort("pageCount"))){
System.out.println(b);
}

Getting book sorted as per pageCount (DESC order)


---------------------------------------------

for(Book b:repository.findAll(new
Sort(Sort.Direction.DESC,"pageCount"))){
System.out.println(b);
}
Getting sorted first sort Book as per aurthor lastName and then as per
pageCount
-----------------------------------------------------------------------------
--------

for(Book b:repository.findAll(new Sort(Sort.Direction.ASC,


"author.lastName", "pageCount"))){
System.out.println(b);
}

Getting more customization


-----------------------------------------------------------------------------
--------

for(Book b:repository.findAll(new
Sort(Sort.Direction.ASC,"author.lastName").and(new
Sort(Sort.Direction.DESC,"pageCount")))){
System.out.println(b);
}

Alternative:
==============

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

public List<Book> findByPageCountGreaterThan(int pageCount, Sort sort);


}

for(Book b:repository.findByPageCountGreaterThan(220, new


Sort("author.firstName"))){
System.out.println(b);
}

Return type for query method:


-----------------------------
=> till now we have just return List<Book>
we can return other type too....like page result

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

public Page<Book> findByPageCountGreaterThan(int pageCount, Pageable


pageable);
}

Using it:
----------
Page page=repository.findByPageCountGreaterThan(120, new PageRequest(0,3));
for (Book b : repository.findByPageCountGreaterThan(120, new
PageRequest(0,3))) {
System.out.println(b);
}

Imp methods of page:


------------------------
//getTotalPages() -- how many pages ?
// getTotalElementMethod() -- how many result available with subset?

Slice?
-----

@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

public Slice<Book> findByPageCountGreaterThan(int pageCount, Pageable


pageable);
}

How to use?
---------
Slice slice = repository.findByPageCountGreaterThan(120, new
PageRequest(0,3));

More efficient then Page, but do not give imp inventory information such as
getTotalPages()

Joins:
---------
one to many:

@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long bookId;
private String title;
private Date publishDate;
private int pageCount;
private double price;

@ManyToOne
@JoinColumn(name = "book_category_id")
private BookCategory bookCategory;
@Entity
@Table(name = "book_category")
public class BookCategory {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;

@OneToMany(mappedBy = "bookCategory", cascade = CascadeType.ALL)


private Set<Book> books=new HashSet<Book>();

@Repository
public interface BookCategoryRepository extends JpaRepository<BookCategory,
Integer>{
}

BookCategory bookCategory=new BookCategory();


bookCategory.setName("IT");
Book b=new Book("java is fun", new Date(), 300, 340);
Book b2=new Book("c is fun", new Date(), 300, 340);

b.setBookCategory(bookCategory);
b2.setBookCategory(bookCategory);

bookCategory.getBooks().add(b2);
bookCategory.getBooks().add(b);

repo.save(bookCategory);

https://roytuts.com/spring-data-jpa-namedquery-and-namedqueries-example/
https://roytuts.com/spring-boot-data-jpa-left-right-inner-and-cross-join-examples/

You might also like