0% found this document useful (0 votes)
27 views11 pages

6 - Spring-Boot 2

Uploaded by

Rahul Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views11 pages

6 - Spring-Boot 2

Uploaded by

Rahul Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Questions

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

Q42) How can I do the Persistence Operations with JPA?


Ans:
EntityManager can be used to perform Persistence Operations.

Q43) How Can I Inject the EntityManager in the required DAO?


Ans:
@PersistentContext

Q44) What is the Speciality of @PersistentContext annotation? How it works


differently from @Autowired/@Resource?
Ans:
*Explained with Diagram*

Q45) What is EntityManager?


Ans:
▪ Each EntityManager instance is associated with a persistence context.
▪ Within the persistence context, the entity instances and their life cycle are managed.
▪ A persistence context is like a cache which contains a set of persistent entities
▪ When Transaction is finished, all persistent objects are detached from the
EntityManager's persistence context and are no longer managed.

Q46) Who is the Provider of @PersistentContext ?


Ans: JPA

Q47) What are the IMP Methods of EntityManager?


Ans:

Q48) When Connection Pool will be created in Spring Boot Application?


Ans: At the Application Start-UP

Q49) When Connection Pool will be created in Spring Application?


Ans: At the Application Start-UP

www.jtcindia.org 58 Spring Boot 2


Spring DATA JPA

 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)

www.jtcindia.org 59 Spring Boot 2


 You need to provide the @EnableJpaRepositories in configuration class

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.

 Spring Data defines a sort of domain-specific language (DSL) where persistence


details are expressed in method signature.

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);
}

 Repository methods are combination of the following 4 things.


1. Verb,
2. Optional Subject,
3. word By,
4. Predicate.

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

www.jtcindia.org 60 Spring Boot 2


 Spring Data allows four verbs in the method name: get, read, find, and count.

 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.

 We can use any of the following comparison operator from property to


parameter:
1) IsAfter, After, IsGreaterThan, GreaterThan
2) IsGreaterThanEqual, GreaterThanEqual
3) IsBefore, Before, IsLessThan, LessThan
4) IsLessThanEqual, LessThanEqual
5) IsBetween, Between
6) IsNull, Null
7) IsNotNull, NotNull
8) IsIn, In
9) IsNotIn, NotIn
10) IsStartingWith, StartingWith, StartsWith
11) IsEndingWith, EndingWith, EndsWith
12) IsContaining, Containing, Contains
13) IsLike, Like
14) IsNotLike, NotLike
15) IsTrue, True
16) IsFalse, False
17) Is, Equals
18) IsNot, Not

www.jtcindia.org 61 Spring Boot 2


 We can sort the results by adding Order By at the end of the method name.
 Sort the results in ascending order by the lastname.

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);

 Although Spring Data Jpa generates an implementation method to query for


almost anything we can imagine

 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.

 Suppose we want to create a repository method to find all customers whose


email address is a G mail address.

 One way to do this is to define a findByEmailLike(String mail) method and pass


in %gmail.com to find G mail users.

List<Customer> findByEmailLike(String mail)

 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();

 We still no need to write the implementation for fetchAllGmailCustomrs()


method. We only give the query, hinting to Spring Data about how it should
implement the method.

www.jtcindia.org 62 Spring Boot 2


 Also, @Query can also be useful if we followed the naming convention, the
method name would be incredibly long. In such situation, we’d probably rather
come up with a shorter method name and use @Query to specify how the
method should query the database.

 The @Query annotation is handy for adding custom query methods to a Spring
Data JPA-enabled interface.

 Sometimes we cannot describe functionality with Spring Data’s method-naming


conventions or even with a query given in the @Query annotation. Such specific
scenarios can be implemented by using EntityManager (from Spring JPA) and
remaining functionalities can be worked with Spring Data i.e., we can combine
EntitityManager from Spring JPA with Spring Data.

 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.

Lab12: Files required

1. MyBootApp.java Updated in Lab12


2. Customer.java Same as Lab11
3. CustomerDAO.java Updated in Lab12
4. application.properties Same as Lab11
5. pom.xml Same as Lab11

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
* */

www.jtcindia.org 63 Spring Boot 2


@SpringBootApplication(scanBasePackages=”com.jtcindia.springboot”) public
class MyBootApp implements CommandLineRunner {

Logger log = LoggerFactory.getLogger(MyBootApp.class);

@Autowired
CustomerDAO custDAO;

public static void main(String[] args) {


SpringApplication.run(MyBootApp.class, args);
}
@Override
public void run(String… args) {
log.info(“My Boot App – run() begin”);
log.info(“ ------------------------------------- “);
// 1. Save()
Customer mycust = new Customer(“som”, “som@jtc”, 12345, “Noida”);
custDAO.save(mycust);

//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));

www.jtcindia.org 64 Spring Boot 2


// 6. findAll(Sort)
System.out.println(“findAll(Sort)”);
List<Customer> list4= custDAO.findAll(Sort.by(Order.desc(“cid”)));
list4.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();

log.info(“My Boot App – run() End”);


log.info(“ ------------------------------------- “);
} }

www.jtcindia.org 65 Spring Boot 2


2. Customer.java
3. CustomerDAO.java
package com.jtcindia.springboot;

import org.springframework.data.jpa.repository.JpaRepository;
/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
public interface CustomerDAO extends JpaRepository<Customer, Integer>{
}

4. application.properties
5. pom.xml

Lab13: Files required

1. MyBootApp.java Updated in Lab13


2. Customer.java Same as Lab12
3. CustomerService.java Newly Added in Lab13
4. CustomerServiceImpl.java Newly Added in Lab13
5. CustomerDAO.java Updated in Lab12
6. application.properties Same as Lab12
7. pom.xml Same as Lab12

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);

www.jtcindia.org 66 Spring Boot 2


@Autowired
CustomerService customerService;

public static void main( String[] args )


{ SpringApplication.run(MyBootApp.class, args);
}

public void run(String... args) throws Exception {


log.info("My Boot App - run() begin");
log.info(" ------------------------------------ ");

Customer cust1=customerService.getCustomerById(501);
System.out.println(cust1);

Customer cust2=customerService.getCustomerOne(501);
System.out.println(cust2);

log.info(" ------------------------------------ ");


log.info("My Boot App - run() END");
}
}

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

package com.jtcindia.springboot; import

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;

www.jtcindia.org 67 Spring Boot 2


/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

@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;
}

@Transactional(propagation = Propagation.REQUIRED,readOnly = true)


public Customer getCustomerOne(int cid) {
Customer cust = customerDAO.getOne(cid);
System.out.println(cust);
return cust;
}
}

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

www.jtcindia.org 68 Spring Boot 2

You might also like