6 - Spring-Boot 2
6 - Spring-Boot 2
Q41) What are the Beans required to Configure for Spring Boot- JPA?
Ans:
We need the following 4 beans but No need to configure these because Spring boot
will to the AutoConfiguration
1) JpaVendorAdaptor
2) DataSource
3) LocalEntityManagerFactory
4) JpaTransactionManager
CURD Operations called Insert, Update , Retrieve and Delete Operations are
common across all DAOs. The only difference is domain types you are
interacting with.
Spring Data internally provides the implementation for all such common
methods.So developer is not responsible for writing implementation for these
common methods.
Ex:
public interface CustomerDAO extends JpaRepository<Customer, Integer>{
//Empty
}
JpaRepository is parameterized and takes two parameters
• Entity class
• Primary Key type
JpaRepository extends CurdRepository.
Both CurdRepository and JpaRepository has 15+ methods for performing
common persistence operations such as saving, deleting, finding
Interface CrudRepository<T,ID>
1) S save(S entity)
2) void deleteById(ID id)
3) void delete(T entity)
4) void deleteAll(Iterable<? extends T> entities)
5) void deleteAll()
6) Optional<T>findById(ID id)
7) long count()
8) Boolean existsById(ID id)
Interface JpaRepository<T,ID>
1) S saveAndFlush(S entity)
2) List<S> saveAll(Iterable<S> entities)
3) List<T> findAll()
4) List<T> findAllById(Iterable<ID> ids)
5) List<T> findAll(Sort sort)
6) void flush()
7) T getOne(ID id)
Ex:
@SpringBootConfiguration
@EnableJpaRepositories(basePackages = "com.jtcindia.springboot") public
class MyBootApplication{
…
}
Spring Data Jpa not only provides implementation for commonly used methods
but also provides a way to add custom methods.
Method signature tells Spring Data everything it needs to know in order to
create an implementation for the method.
Ex:
public interface CustomerDAO extends JpaRepository<Customer, Integer>{
public List<Customer> findCustomerByCname(String name);
public List<Customer> findCustomerByEmail(String email);
public List<Customer> findByPhone(long phone);
public List<Customer> getCustomerByEmailAndPhone(String email,long phone);
public List<Customer> getCustomerByEmailOrPhone(String email,long phone);
}
Ex1:
findCustomerByEmail(String email)
find is verb
Customer is subject
By is word
Email is predicate
Ex2:
findByEmail(String email)
find is verb
the subject isn’t specified and is implied to be a Customer.
By is word
Email is predicate
The get, read, and find verbs are synonymous; all three result in repository
methods that query for data and return object(s).
The count verb, on the other hand, returns a count of matching objects, rather
than the objects themselves.
Ex3:
readCustomerByEmailOrPhone(String email, long phone)
read is verb
Customer is subject
By is word
EmailOrPhone is predicate
The predicate is the most interesting and important part of the method name.
Ex:
List<Customer> readByFirstnameOrLastnameAllIgnoresCase(String first, String last);
List<Customer> readByLastnameOrderByLastnameAsc(String last);
Sort results in ascending order by the firstname and descending order by the
lastname.
Ex:
List<Customer>
readByFirstnameOrLastnameOrderByFirstnameAscLastnameDesc(String first, String
last);
Spring Data DSL has its limitations, and sometimes it isn’t convenient or even
possible to express the desired query in a method name.
When that happens, Spring Data provides @Query annotation to write query
explicitly.
Another way to do this is that we can use the @Query annotation to provide
Spring Data with the query that should be performed.
@Query("select cust from Customer cust where cust.email like '%gmail.com' ")
Public List<Customer> fetchOnlyGmailCustomers();
The @Query annotation is handy for adding custom query methods to a Spring
Data JPA-enabled interface.
The Spring Data Jpa generates the implementation class for a repository
interface whose name is same as interface’s name and post fixed with impl.
1. MyBootApp.java
package com.jtcindia.springboot;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
/*
* @Author : Som Prakash
* @company : JTCINDIA
* */
@Autowired
CustomerDAO custDAO;
//2. saveAndFlush()
mycust = new Customer(“som”, “som@jtc”, 12345, “Noida”);
custDAO.saveAndFlush(mycust);
//3.saveAll()
Customer cust1 = new Customer(“s”, “A@jtc”, 5555,
“Noida”); Customer cust2 = new Customer(“B”, “B@jtc”,
5555, “Noida”); List<Customer> list=new ArrayList<>();
list.add(cust1);
list.add(cust2);
custDAO.saveAll(list);
// 4. findAll
System.out.println(“findAll”);
List<Customer> list1= custDAO.findAll();
list1.forEach(cust -> System.out.println(cust));
//5.findAllById(list);
List<Integer> idList=new ArrayList<>();
idList.add(32);
idList.add(33);
idList.add(34);
List<Customer> list2= custDAO.findAllById(idList);
list2.forEach(cust -> System.out.println(cust));
System.out.println(“findAll(Sort)”);
List<Customer> list5= custDAO.findAll(Sort.by(Order.asc(“cname”)));
list5.forEach(cust -> System.out.println(cust));
//7.deleteById(Id)
custDAO.deleteById(1);
//8.delete(entity)
custDAO.delete(cust4);
//9.deleteAll(list);
List<Customer> custList=new ArrayList<>();
Customer cust1 = new Customer(“A”, “A@jtc”, 5555,
“Noida”); Customer cust2 = new Customer(“B”, “B@jtc”,
5555, “Noida”); custList.add(cust1);
custList.add(cust2);
custDAO.deleteAll(custList);
//10.deleteAll()
// custDAO.deleteAll();
//11.existsById(ID id)
oolean b= custDAO.existsById(25);
System.out.println(b);
b= custDAO.existsById(9);
System.out.println(b);
//12.count()
long count= custDAO.count();
System.out.println(count);
//13.flush()
custDAO.flush();
import org.springframework.data.jpa.repository.JpaRepository;
/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
public interface CustomerDAO extends JpaRepository<Customer, Integer>{
}
4. application.properties
5. pom.xml
1. MyBootApp.java
package com.jtcindia.springboot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
@SpringBootApplication
public class MyBootApp implements CommandLineRunner{
static final Logger log = LoggerFactory.getLogger(MyBootApp.class);
Customer cust1=customerService.getCustomerById(501);
System.out.println(cust1);
Customer cust2=customerService.getCustomerOne(501);
System.out.println(cust2);
2. Customer.java
3. CustomerService.java
package com.jtcindia.springboot;
/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
public interface CustomerService {
public Customer getCustomerById(int cid);
public Customer getCustomerOne(int cid);
}
4. CustomerServiceImpl.java
java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Autowired
CustomerDAO customerDAO;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Customer getCustomerById(int cid) {
Optional<Customer> opt = customerDAO.findById(cid);
System.out.println(opt);
if(opt.isPresent()) {
return opt.get();
}
return null;
}
5. CustomerDAO.java
package com.jtcindia.springboot;
import org.springframework.data.jpa.repository.JpaRepository;
/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
public interface CustomerDAO extends JpaRepository<Customer, Integer>{
}
6. application.properties
7. pom.xml