📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Create JPA Entity
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@Entity
@Table(name = "persons")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
}
Create Spring Data JPA Repository - PersonRepository
Let's create an PersonRepository interface that extends the JpaRepository interface from Spring Data JPA:
import com.springdatajpa.springboot.entity.Person;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PersonRepository extends JpaRepository<Person, Long> {
}
Deleting Entities by List of IDs
void deleteByIdIn(List<Long> ids);
Implementing in the Service Layer
@Service
public class PersonService {
@Autowired
private PersonRepository personRepository;
@Transactional
public void deletePersonsByListOfIds(List<Long> ids) {
personRepository.deleteByIdIn(ids);
}
}
Safety Considerations
Testing the Implementation
@SpringBootTest
public class PersonServiceTest {
@Autowired
private PersonService personService;
@Autowired
private PersonRepository personRepository;
@Test
public void testDeleteByListOfIds() {
// Given: Initial data
Person john = personRepository.save(new Person("John", "123 Elm Street"));
Person jane = personRepository.save(new Person("Jane", "456 Maple Avenue"));
List<Long> idsToDelete = Arrays.asList(john.getId(), jane.getId());
// When: Deleting persons by IDs
personService.deletePersonsByListOfIds(idsToDelete);
// Then: Assert that the persons are deleted
assertTrue(personRepository.findById(john.getId()).isEmpty());
assertTrue(personRepository.findById(jane.getId()).isEmpty());
}
}
Comments
Post a Comment
Leave Comment