Performing basic CRUD (Create, Read, Update, Delete) operations using Spring Boot and Hibernate is a common task in developing database-driven applications. Here is an overview of how to perform CRUD operations using Spring Boot and Hibernate:
Create operation: To create a new entity, you need to instantiate an object of the corresponding class and save it using the save() method of the Hibernate Session or EntityManager object. Here is an example of creating a new User entity:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void createUser(String firstName, String lastName) {
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
userRepository.save(user);
}
}
Read operation: To retrieve an entity, you can use the findById() method of the Hibernate Session or EntityManager object, or use one of the Spring Data findById() or findAll() methods provided by the repository interface. Here is an example of retrieving a User entity by ID:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
Update operation: To update an entity, you need to retrieve it using the findById() method, modify its properties, and save it using the save() method of the Hibernate Session or EntityManager object. Here is an example of updating a User entity:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void updateUser(Long id, String firstName, String lastName) {
User user = userRepository.findById(id).orElse(null);
if (user != null) {
user.setFirstName(firstName);
user.setLastName(lastName);
userRepository.save(user);
}
}
}
Delete operation: To delete an entity, you can use the delete() method of the Hibernate Session or EntityManager object, or use one of the Spring Data deleteById() or delete() methods provided by the repository interface. Here is an example of deleting a User entity by ID:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
Overall, performing basic CRUD operations using Spring Boot and Hibernate is a straightforward process that involves using the appropriate methods provided by the Hibernate Session or EntityManager object, or the repository interface. By using these methods, developers can easily create, read, update, and delete entities without having to write boilerplate SQL code.