import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Optional; @RestController @RequestMapping("/users") public class UserController { private final UserRepository userRepository; public UserController(UserRepository userRepository) { this.userRepository = userRepository; } @GetMapping("/{id}") public ResponseEntity<User> getUser(@PathVariable Long id) { Optional<User> user = userRepository.findById(id); if (user.isPresent()) { return ResponseEntity.ok(user.get()); } else { return ResponseEntity.notFound().build(); } } }
The method returns ResponseEntity.notFound().build() when the user is not found, which corresponds to HTTP 404 Not Found status. If the user is found, it returns HTTP 200 OK with the user data.
import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class OrderService { @Transactional public void placeOrder(Order order) { // save order to database // update inventory // send confirmation } }
The @Transactional annotation starts a transaction at method start and commits it if the method completes without exceptions. So the transaction is committed and closed after the method finishes.
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.jdbc.DriverThe driver class name com.mysql.jdbc.Driver is deprecated in newer MySQL drivers. The correct driver class name is com.mysql.cj.jdbc.Driver. Using the old name causes connection failure.
JpaRepository is an interface and must be extended, not implemented. It requires two generic parameters: the entity class and the ID type. Option A correctly follows this pattern.
Spring uses proxies for @Transactional. When a method in the same class calls another method, the call does not go through the proxy, so the inner method's @Transactional annotation is ignored and runs without a transaction.