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

Spring Boot JPA Configuration Guide

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)
14 views11 pages

Spring Boot JPA Configuration Guide

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

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

[Link] 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
[Link] 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)

[Link] 59 Spring Boot 2


 You need to provide the @EnableJpaRepositories in configuration class

Ex:
@SpringBootConfiguration
@EnableJpaRepositories(basePackages = "[Link]") 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

[Link] 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

[Link] 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 %[Link] 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 [Link] like '%[Link]' ")
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.

[Link] 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. [Link] Updated in Lab12


2. [Link] Same as Lab11
3. [Link] Updated in Lab12
4. [Link] Same as Lab11
5. [Link] Same as Lab11

1. [Link]
package [Link];

import [Link].*;
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/*
* @Author : Som Prakash
* @company : JTCINDIA
* */

[Link] 63 Spring Boot 2


@SpringBootApplication(scanBasePackages=”[Link]”) public
class MyBootApp implements CommandLineRunner {

Logger log = [Link]([Link]);

@Autowired
CustomerDAO custDAO;

public static void main(String[] args) {


[Link]([Link], args);
}
@Override
public void run(String… args) {
[Link](“My Boot App – run() begin”);
[Link](“ ------------------------------------- “);
// 1. Save()
Customer mycust = new Customer(“som”, “som@jtc”, 12345, “Noida”);
[Link](mycust);

//2. saveAndFlush()
mycust = new Customer(“som”, “som@jtc”, 12345, “Noida”);
[Link](mycust);

//[Link]()
Customer cust1 = new Customer(“s”, “A@jtc”, 5555,
“Noida”); Customer cust2 = new Customer(“B”, “B@jtc”,
5555, “Noida”); List<Customer> list=new ArrayList<>();
[Link](cust1);
[Link](cust2);
[Link](list);

// 4. findAll
[Link](“findAll”);
List<Customer> list1= [Link]();
[Link](cust -> [Link](cust));

//[Link](list);
List<Integer> idList=new ArrayList<>();
[Link](32);
[Link](33);
[Link](34);
List<Customer> list2= [Link](idList);
[Link](cust -> [Link](cust));

[Link] 64 Spring Boot 2


// 6. findAll(Sort)
[Link](“findAll(Sort)”);
List<Customer> list4= [Link]([Link]([Link](“cid”)));
[Link](cust -> [Link](cust));

[Link](“findAll(Sort)”);
List<Customer> list5= [Link]([Link]([Link](“cname”)));
[Link](cust -> [Link](cust));

//[Link](Id)
[Link](1);

//[Link](entity)
[Link](cust4);

//[Link](list);
List<Customer> custList=new ArrayList<>();
Customer cust1 = new Customer(“A”, “A@jtc”, 5555,
“Noida”); Customer cust2 = new Customer(“B”, “B@jtc”,
5555, “Noida”); [Link](cust1);
[Link](cust2);

[Link](custList);

//[Link]()
// [Link]();

//[Link](ID id)
oolean b= [Link](25);
[Link](b);

b= [Link](9);
[Link](b);

//[Link]()
long count= [Link]();
[Link](count);

//[Link]()
[Link]();

[Link](“My Boot App – run() End”);


[Link](“ ------------------------------------- “);
} }

[Link] 65 Spring Boot 2


2. [Link]
3. [Link]
package [Link];

import [Link];
/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
public interface CustomerDAO extends JpaRepository<Customer, Integer>{
}

4. [Link]
5. [Link]

Lab13: Files required

1. [Link] Updated in Lab13


2. [Link] Same as Lab12
3. [Link] Newly Added in Lab13
4. [Link] Newly Added in Lab13
5. [Link] Updated in Lab12
6. [Link] Same as Lab12
7. [Link] Same as Lab12

1. [Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
@SpringBootApplication
public class MyBootApp implements CommandLineRunner{
static final Logger log = [Link]([Link]);

[Link] 66 Spring Boot 2


@Autowired
CustomerService customerService;

public static void main( String[] args )


{ [Link]([Link], args);
}

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


[Link]("My Boot App - run() begin");
[Link](" ------------------------------------ ");

Customer cust1=[Link](501);
[Link](cust1);

Customer cust2=[Link](501);
[Link](cust2);

[Link](" ------------------------------------ ");


[Link]("My Boot App - run() END");
}
}

2. [Link]
3. [Link]
package [Link];
/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
public interface CustomerService {
public Customer getCustomerById(int cid);
public Customer getCustomerOne(int cid);
}

4. [Link]

package [Link]; import

[Link];
import [Link];
import [Link];
import [Link];
import [Link];

[Link] 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 = [Link](cid);
[Link](opt);
if([Link]()) {
return [Link]();
}
return null;
}

@Transactional(propagation = [Link],readOnly = true)


public Customer getCustomerOne(int cid) {
Customer cust = [Link](cid);
[Link](cust);
return cust;
}
}

5. [Link]
package [Link];

import [Link];
/*
* @Author : SomPrakash
* @company : JTCINDIA
* */
public interface CustomerDAO extends JpaRepository<Customer, Integer>{
}

6. [Link]
7. [Link]

[Link] 68 Spring Boot 2

Common questions

Powered by AI

Spring Data provides a DSL for repository methods to express persistence operations directly in the method names, allowing developers to write less code while still performing complex queries. The DSL supports various query predicates and sort operations, making data access more intuitive and domain-specific. However, it has limitations; certain complex queries cannot be expressed purely through method naming conventions. In such cases, developers must employ the @Query annotation or use EntityManager to handle more complex interactions .

CrudRepository and JpaRepository offer a range of common operations such as saving, deleting, and finding entities. Operations include methods like save(), deleteById(), findAll(), and count(), reducing boilerplate code by providing default implementations for these operations. These readily available methods are significant for developers because they increase productivity, allowing them to focus on domain-specific logic instead of routine data access code .

Spring Boot supports connection pooling by auto-configuring connection pool beans like HikariCP, Tomcat, or Commons DBCP based on the dependencies available in the classpath. The connection pool is created at application startup, allowing subsequent database operations to be served by these pre-established connections. This approach improves the performance of JPA applications by reducing the cost associated with opening and closing database connections .

The @PersistentContext annotation is specifically used for injecting an EntityManager in JPA. While @Autowired and @Resource are used for dependency injection in Spring, @PersistentContext manages the entity lifecycle within a persistence context, acting like a cache. Unlike @Autowired/@Resource, which inject dependencies outside a transaction scope, @PersistentContext ensures that entities are managed during a transaction and are detached once it completes, offering fine-tuned context management .

For complex queries, Spring Data JPA allows the use of the @Query annotation to define custom JPQL or SQL queries directly. This feature is particularly useful when method names become unwieldy or cannot express the desired operations. The @Query annotation provides a flexible way to define queries without writing the implementations, letting developers express complex logic or concatenate strings to form dynamic queries .

In Spring Data JPA, repository method names consist of a combination of verbs, optional subjects, mandatory 'By' words, and predicates, which help form database queries. Verbs like get, read, find, and count define the operation: whether to retrieve objects or count them. Predicates, on the other hand, specify conditional logic such as IsGreaterThan or IsLessThanEqual, allowing methods to express filtering criteria. Example methods include findByEmail and readCustomerByEmailOrPhone, where find/read are verbs, 'By' denotes condition, and 'Email'/'Phone' act as predicates .

Spring Boot simplifies JPA application development through its auto-configuration capabilities, automatically setting up common configurations like DataSource, EntityManager, and Transaction management. It eliminates the need for extensive XML configurations or manual bean setups by detecting JPA dependencies on the classpath, applying sensible defaults, and offering an easily customizable application.properties file. This feature enables rapid application development, higher productivity, and less configuration-related errors, allowing developers to implement business logic more efficiently .

Spring Boot automatically configures beans such as JpaVendorAdaptor, DataSource, LocalEntityManagerFactory, and JpaTransactionManager. Manual configuration is unnecessary because Spring Boot provides auto-configuration for these components, simplifying the setup and allowing developers to focus on the application logic without worrying about the underlying infrastructure setup .

JpaVendorAdapter is crucial in Spring Boot JPA configuration because it abstracts the vendor-specific details required by JPA, including dialects, specific features, and optimizations. It acts as a configuration point that applies these vendor-specific settings to the EntityManagerFactory. By using JpaVendorAdapter, developers can switch between different JPA implementations with minimal changes, enhancing application portability. This adapter streamlines vendor integration, reduces boilerplate configuration, and facilitates adapting to different database environments easily .

A developer might choose @Query annotation over method naming conventions in Spring Data JPA when method names become excessively long or complex, exceeding reasonable readability or maintainability. The @Query annotation allows for direct JPQL or SQL query definitions, providing the flexibility to articulate constraints and operations that cannot be expressed effectively within the limitations of method names. Additionally, it supports dynamic query execution without needing explicit implementation coding, improving developer efficiency .

You might also like