Spring Data JPA Interview Questions and Answers
1. What does JPA stand for?
Java Persistence API
2. What's the difference between JPA and Spring Data JPA?
JPA is a specification that standardizes the way Java Objects are mapped to a relational database system. Being just a specification, JPA consists of a set of interfaces, like EntityManagerFactory, EntityManager, and annotations that avail you to map a Java entity object to a database table. There are several JPA providers, like Hibernate, EclipseLink, or Open JPA which you can utilize.
Spring Data JPA is not an implementation or JPA provider, it's just an abstraction used to significantly minimize the quantity of boilerplate code required to implement data access layers for various persistence stores.
3. What Is the Difference Between Hibernate and Spring Data JPA?
Hibernate is a JPA implementation, while Spring Data JPA is a JPA Data Access Abstraction. Spring Data offers a solution to GenericDao custom implementations. It can withal engender JPA queries on your behalf through method name conventions.
Spring Data JPA is not an implementation or JPA provider, it's just an abstraction used to significantly minimize the quantity of boilerplate code required to implement data access layers for various persistence stores.
4. What does the @Id annotation do?
The @Id annotation is utilized to designate the identifier property of the entity bean. The placement of the @Id annotation determines the default access strategy that Hibernate will utilize for the mapping. If the @Id annotation is placed over the field, then filed access will be utilized.
For Example,
@Entitypublic class User {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; // TODO
}
The User object’s id property is annotated with @Id so that JPA recognizes it as the object’s ID. The id property is also annotated with @GeneratedValue to indicate that the ID should be generated automatically.
5. What does the @Entity annotation do?
@Entity annotation defines that a class can be mapped to a table. And that is it, it is just a marker, like for example Serializable interface.
For Example,
@Entitypublic class User {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; // TODO
}
The User class is annotated with @Entity, indicating that it is a JPA entity. (Because no @Table annotation exists, it is assumed that this entity is mapped to a table named Customer.)
6. What does the @Column annotation do?
The @Column annotation is utilized to designate the details of the column to which a field or property will be mapped.
For Example,
@Column(name="DESC", nullable=false, length=512) public String getDescription() { return description; }
7. What does the @GeneratedValue annotation do?
The @GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.
For Example,
@Entitypublic class User {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; // TODO
}
The User object’s id property is annotated with @Id so that JPA recognizes it as the object’s ID. The id property is also annotated with @GeneratedValue to indicate that the ID should be generated automatically.
8. What is the difference between FetchType.Eager and FetchType.Lazy?
FetchType.LAZY = This does not load the relationships unless we invoke it via the getter method. Lazy initialization ameliorates performance by avoiding nonessential computation and minimising memory requisites.
For Example,
@Entitypublic class User {
@Id private String id;
private String name;
private String address;
@OneToMany(fetch = FetchType.LAZY) private List<User> users;
// TODO. }
FetchType.EAGER = This loads all the relationships. Eager initialization takes more memory consumption and processing speed is slow.
For Example,
@Entitypublic class User {
@Id private String id;
private String name;
private String address;
@OneToMany(fetch = FetchType.EAGER) private List<User> users;
// TODO. }
9. What does the @EnableJpaRepositories annotation do?
This annotation enables the automatic generation of JPA repositories. Any class which implements the CrudRepository interface will engender a repository when this annotation is present.
For Example,
@EnableJpaRepositories(basePackages = "com.knowledgefactory.dev.jpa.repositories")
10. What does the @EntityScan Annotation do?
If the entity classes are not placed in the main application package or its subpackage(s), then it is required to declare the package(s) in the main configuration class with @EntityScan annotation. This will tells spring boot to where to scan for detecting the entities for the application. Basically, @EnableAutoConfiguration will scan the given package(s) for detecting the entities.
For Example,
@EntityScan(basePackages = "com.knowledgefactory.dev.demo")
11. What does the @Query Annotation do?
In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute.
For Example,
JPQL
@Query("SELECT u FROM User u WHERE u.status = 1")Collection<User> findAllActiveUsers();
SQL
@Query(value = "SELECT * FROM USERS u WHERE u.status = 1", nativeQuery = true)Collection<User> findAllActiveUsers();
12. How can we create a custom repository in Spring Data JPA?
To create a custom repository, we have to extend it to any of the following interfaces:
- Repository
public interface UserRepository extends Repository<User, Long> { List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);}
- PagingAndSortingRepository
@Repositorypublic interface EmployeeRepository extends PagingAndSortingRepository<EmployeeEntity, Long> {
}
- CrudRepository
public interface UserRepository extends CrudRepository<User, Long> {}
- JpaRepository
public interface UserRepository extends JpaRepository<User, Long> { }
- QueryByExampleRepository
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {}
13. What is the difference between CrudRepository, JpaRepository, and PagingAndSortingRepository interfaces in Spring Data JPA?
JpaRepository extends PagingAndSortingRepository which in turn elongates CrudRepository.
Their main functions are:
- CrudRepository mainly provides CRUD functions.
- PagingAndSortingRepository provides methods to do pagination and sorting records.
- JpaRepository contains the full API of CrudRepository and PagingAndSortingRepository. So it contains API for basic CRUD operations and also API for pagination and sorting.
14. @NamedQuery vs @NamedNativeQuery in Spring Data JPA?
@NamedQuery and @NamedNativeQuery annotations are used with entity class.
@NamedQuery example.
@Entity@NamedQuery(name = "User.findByName", query = "select s from User s where s.name = ?1")public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "name") private String name; //TODO}
@NamedNativeQuery example
@Entity@NamedNativeQuery(name = "User.findByName", query = "select * from User where name = ?1", resultClass = User.class)public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "name") private String name; //TODO}
15. What are the important methods of Crudrepository to perform CRUD operations in Spring Data JPA?
The Crudrepository contains below methods.
- save(S entity): the save() method allows us to save an entity to the DB.
- saveAll(Iterable<S>): It is used to save all the entities to database.
- findById(ID id): findById method retrieves an entity by its id.
- existsById(ID id): check entity exists with this id or not.
- findAll(): returns all entities that are saved to the database.
- findAllById(Iterable<ID> ids): Return all entity of given ids.
- count(): Returns the number of entities
- deleteById(ID id): Delete the entity on basis of id.
- delete(T entity): delete the entity.
- delete(Iterable<? extends T> entities): Deletes all entities that match in the given iterable.
More Java interview questions and answers...
- Spring Boot actuator interview questions and answers
- Spring Webflux Interview Questions and Answers
- Spring Core - Interview Questions
- Top Spring Cloud Interview Questions
- Spring Security Interview Questions
- Spring MVC - Interview Questions
- Spring Webflux Interview Questions
- Top Spring Boot Interview Questions
- Spring Data JPA Interview Questions and Answers
- Top Mockito Interview Questions and Answers
- Java Collections Interview Questions
- Java Stream API Interview Questions and Answers - Frequently asked
- Quarkus - Interview questions and answers
- Spring Interview questions and answers