0% found this document useful (0 votes)
12 views10 pages

Assignment 6

Uploaded by

Aman Kumar.
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)
12 views10 pages

Assignment 6

Uploaded by

Aman Kumar.
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/ 10

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;

private String name;

// Getters and setters


}
2. Define a custom repository interface:
java
Copy code
public interface StudentCustomRepository {
List<Student> findStudentsWithCustomLogic();
}
3. Provide the implementation for the custom repository:
java
Copy code
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

public class StudentCustomRepositoryImpl implements


StudentCustomRepository {

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

public void customLogic() {


List<Student> students =
studentRepository.findStudentsWithCustomLogic();
students.forEach(student -> System.out.println(student.getName()));
}
}

Q.2 Explain the difference between FetchType.EAGER and FetchType.LAZY


with code.
FetchType.EAGER: Loads the related entity immediately along with the parent
entity.
FetchType.LAZY: Delays loading of the related entity until it is explicitly
accessed.
Example:
java
Copy code
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToMany(mappedBy = "department", fetch = FetchType.LAZY) //


Change to FetchType.EAGER for immediate loading
private List<Employee> employees;

// Getters and setters


}

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Getters and setters
}
Difference in action:
java
Copy code
@Autowired
private DepartmentRepository departmentRepository;

public void testFetchType() {


Department department = departmentRepository.findById(1L).get();

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;

public void saveStudent() {


Student student = new Student();
student.setName("John Doe");
studentRepository.save(student); // Insert operation

student.setName("John Updated");
studentRepository.save(student); // Update operation
}
}

Q.4 Steps to update an entity with an example (StudentEntity.java).


Steps:
1. Fetch the entity from the database.
2. Modify the entity fields.
3. Use the save() method to persist changes.
StudentEntity.java:
java
Copy code
@Entity
public class StudentEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long s_id;

private String s_name;

// Getters and setters


}
Repository:
java
Copy code
public interface StudentRepository extends JpaRepository<StudentEntity,
Long> {
}
Update Logic:
java
Copy code
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;

public void updateStudent(Long id, String newName) {


StudentEntity student = studentRepository.findById(id)
.orElseThrow(() -> new RuntimeException("Student not found"));

student.setS_name(newName);
studentRepository.save(student); // Update operation
}
}

Q.5 Explain Cache dependency, with implementation.


Cache Dependency means caching is dependent on certain factors like
database state, method execution results, or cache relationships.
Implementation Example Using Spring Cache:
1. Enable caching in the application.
java
Copy code
@SpringBootApplication
@EnableCaching
public class CacheExampleApplication {
public static void main(String[] args) {
SpringApplication.run(CacheExampleApplication.class, args);
}
}
2. Create a cacheable service.
java
Copy code
@Service
public class StudentService {

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

Q.6 Difference between @CachePut and @CacheEvict with an example.


• @CachePut: Updates the cache without evicting it.
• @CacheEvict: Removes entries from the cache.
Example:
java
Copy code
@Service
public class StudentService {

@Cacheable(value = "students", key = "#id")


public Student getStudent(Long id) {
System.out.println("Fetching student...");
return studentRepository.findById(id).get();
}

@CachePut(value = "students", key = "#student.s_id")


public Student updateStudent(Student student) {
System.out.println("Updating student...");
return studentRepository.save(student); // Updates the cache
}

@CacheEvict(value = "students", key = "#id")


public void deleteStudent(Long id) {
System.out.println("Deleting student...");
studentRepository.deleteById(id); // Removes from cache
}
}
Usage:
java
Copy code
studentService.getStudent(1L); // Fetches and caches
studentService.updateStudent(student); // Updates cache
studentService.deleteStudent(1L); // Evicts cache entry
• @CachePut: Ensures the cache is updated with the new value.
• @CacheEvict: Removes the entry from the cache.

You might also like