Assignment 6
Assignment 6
Q.1 How to create a custom repository in Spring Data JPA? Explain with an
example.
Spring Data JPA allows you to define custom behavior in repositories by
implementing a custom interface.
Steps to create a custom repository:
1. Create a repository interface that extends JpaRepository.
2. Define a custom interface and its implementation for additional
methods.
3. Combine the custom interface with the main repository.
Example:
1. Create the entity:
java
Copy code
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@PersistenceContext
private EntityManager entityManager;
@Override
public List<Student> findStudentsWithCustomLogic() {
return entityManager.createQuery("SELECT s FROM Student s WHERE
LENGTH(s.name) > 5", Student.class)
.getResultList();
}
}
4. Extend the custom repository in the main repository:
java
Copy code
public interface StudentRepository extends JpaRepository<Student, Long>,
StudentCustomRepository {
}
5. Use the repository in your service:
java
Copy code
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Getters and setters
}
Difference in action:
java
Copy code
@Autowired
private DepartmentRepository departmentRepository;
System.out.println("Department Loaded!");
// Accessing employees
System.out.println("Employees: " + department.getEmployees()); // Loaded
only for LAZY, EAGER loads earlier
}
• FetchType.LAZY: Employees are fetched only when getEmployees() is
accessed.
• FetchType.EAGER: Employees are loaded immediately when the
department is fetched.
Q.3 What is the purpose of the CrudRepository save() method in Spring Data
JPA?
The save() method in CrudRepository is used to insert or update an entity.
• If the entity does not have an ID, it performs an insert.
• If the entity has an ID, it updates the existing record.
Example:
java
Copy code
public interface StudentRepository extends CrudRepository<Student, Long> {
}
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
student.setName("John Updated");
studentRepository.save(student); // Update operation
}
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long s_id;
student.setS_name(newName);
studentRepository.save(student); // Update operation
}
}
@Cacheable("students")
public Student getStudentById(Long id) {
System.out.println("Fetching student from database...");
return studentRepository.findById(id).get();
}
}
3. When the cache is updated or invalidated, changes will reflect based on
configuration.