Spring Data JPA | Hibernate | Transactions | Lazy Loading | SQL | Programming
Duration: 20 Minutes
Experience: 5–10 Years
This assessment evaluates production-level knowledge of Spring Data JPA and Hibernate, including entity relationships, transactions, fetching strategies, locking, SQL, and Java 8 Streams.
Section A – Spring Data JPA & Hibernate MCQs
Question 1 – Fetch Type
Consider the following entity.
@Entity
class Department {
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
If no fetch type is specified, what is the default fetch type?
A. LAZY
B. EAGER
C. Depends on the database
D. Depends on Spring Boot version
Question 2 – LazyInitializationException
Which scenario most commonly causes a LazyInitializationException?
A. Accessing a lazy-loaded collection after the Hibernate Session has been closed.
B. Calling save() twice.
C. Executing multiple SQL statements in one transaction.
D. Using @Transactional.
Question 3 – @Transactional
@Service
public class EmployeeService {
@Transactional
public void save(Employee employee){
repository.save(employee);
throw new RuntimeException();
}
}
What happens?
A. Employee is committed.
B. Employee is rolled back.
C. Compilation Error.
D. Employee is committed only if using Oracle.
Question 4 – N+1 Query Problem
Which solution is most appropriate for avoiding the N+1 query problem?
A. Increase the JDBC connection pool size.
B. Use JOIN FETCH or @EntityGraph.
C. Replace Hibernate with JDBC.
D. Increase JVM heap memory.
Question 5 – Optimistic Locking
Which annotation enables optimistic locking in JPA?
A.
@Lock
B.
@Optimistic
C.
@Version
D.
@Transactional
Section B – SQL Challenge
Question 6
Tables
DEPARTMENT
| DEPT_ID | NAME |
|---|---|
| 10 | IT |
| 20 | HR |
EMPLOYEE
| EMP_ID | NAME | DEPT_ID | SALARY |
|---|---|---|---|
| 1 | John | 10 | 6000 |
| 2 | Steve | 10 | 8000 |
| 3 | Mary | 20 | 7000 |
Query
SELECT D.NAME,
MAX(E.SALARY)
FROM DEPARTMENT D
JOIN EMPLOYEE E
ON D.DEPT_ID = E.DEPT_ID
GROUP BY D.NAME;
Which output is correct?
A.
IT 8000
HR 7000
B.
IT 6000
HR 7000
C.
IT 14000
HR 7000
D.
Compilation Error
Section C – Programming Questions
Question 7 – Sort Employees
Given
class Employee{
private String name;
private int salary;
}
Using Java 8 Streams:
- Sort employees by salary in descending order.
- If salaries are equal, sort by name.
Question 8 – Department Wise Employee Count
Given
class Employee{
private String department;
}
Using Java 8 Streams, print the number of employees in each department.
Expected Output
IT -> 5
HR -> 3
Finance -> 2
Question 9 – Merge Two Sorted Arrays
Write a Java program to merge two sorted arrays into one sorted array.
Example
Array1
1 3 5 7
Array2
2 4 6 8
Expected Output
1 2 3 4 5 6 7 8
Bonus:
Solve without calling Arrays.sort() after merging.
Answer Key & Detailed Explanations
Question 1
Correct Answer: A
Explanation
Default fetch types in JPA are:
| Relationship | Default Fetch |
|---|---|
@ManyToOne | EAGER |
@OneToOne | EAGER |
@OneToMany | LAZY |
@ManyToMany | LAZY |
Therefore, employees is loaded lazily.
Interview Follow-up
Why is @ManyToOne eager by default, and why do many projects explicitly change it to LAZY?
Question 2
Correct Answer: A
Explanation
Lazy collections are loaded only when accessed.
If the Hibernate Session (Persistence Context) has already been closed, Hibernate cannot fetch the data and throws:
LazyInitializationException
Common solutions:
JOIN FETCH@EntityGraph- DTO Projection
- Access within an active transaction
Avoid using Open Session in View (OSIV) as the default solution for performance-sensitive applications.
Question 3
Correct Answer: B
Explanation
A RuntimeException marks the transaction for rollback by default.
Therefore:
save()
↓
RuntimeException
↓
Transaction Rollback
Nothing is committed.
Question 4
Correct Answer: B
Explanation
The N+1 problem occurs when:
- One query loads parent entities.
- Additional queries load child entities one at a time.
Example
1 query for Departments
+
100 queries for Employees
Best solutions:
JOIN FETCH@EntityGraph- DTO projection for read-only APIs
Question 5
Correct Answer: C
Explanation
@Version
private Long version;
Every update increments the version.
If another transaction has already updated the same row, Hibernate throws:
OptimisticLockException
This prevents lost updates without locking database rows.
Question 6
Correct Answer: A
Explanation
Maximum salary:
| Department | Maximum |
|---|---|
| IT | 8000 |
| HR | 7000 |
Query result
IT 8000
HR 7000
Question 7 – Sample Solution
employees.stream()
.sorted(
Comparator.comparing(Employee::getSalary)
.reversed()
.thenComparing(Employee::getName))
.forEach(System.out::println);
Concepts Tested
- Comparator chaining
reversed()- Method References
Complexity
Time: O(n log n)
Space: O(n)
Question 8 – Sample Solution
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.counting()))
.forEach((k,v)->
System.out.println(k+" -> "+v));
Concepts Tested
groupingBy()counting()- Streams
Complexity
Time: O(n)
Space: O(n)
Question 9 – Sample Solution
int i = 0;
int j = 0;
List<Integer> result = new ArrayList<>();
while(i < arr1.length && j < arr2.length){
if(arr1[i] <= arr2[j]){
result.add(arr1[i++]);
}else{
result.add(arr2[j++]);
}
}
while(i < arr1.length){
result.add(arr1[i++]);
}
while(j < arr2.length){
result.add(arr2[j++]);
}
System.out.println(result);
Complexity
| Algorithm | Time | Space |
|---|---|---|
| Merge Sorted Arrays | O(n + m) | O(n + m) |
This is more efficient than concatenating both arrays and sorting again, which would require O((n+m) log(n+m)) time.
Evaluation Guide
| Score | Recommendation |
|---|---|
| 9/9 | Excellent – Strong Spring Data JPA Developer |
| 7–8 | Good – Proceed to Technical Round |
| 5–6 | Average – Requires Further Evaluation |
| Below 5 | Not Recommended |
Interviewer’s Notes
This set evaluates production-ready persistence concepts.
A strong candidate should be able to explain:
- Default JPA fetch strategies.
- Why
LazyInitializationExceptionoccurs and how to avoid it. - Transaction rollback behavior with checked and unchecked exceptions.
- The N+1 query problem and why
JOIN FETCHor@EntityGraphis preferred. - How optimistic locking using
@Versionprevents lost updates. - How comparator chaining works with Java 8 Streams.
- Why merging two sorted arrays in linear time is more efficient than sorting after concatenation.
Candidates who can discuss DTO projections, pagination, batching, second-level caching, and optimistic versus pessimistic locking usually have solid production experience with Spring Data JPA and Hibernate.