JPA helps by automatically linking Java objects to database tables. This means developers write less SQL and focus more on Java code, making the app easier to maintain.
import jakarta.persistence.*; @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // getters and setters } // In a Spring Boot service: Product p = new Product(); p.setName("Book"); productRepository.save(p); Long savedId = p.getId();
The @GeneratedValue annotation tells JPA to let the database generate a unique ID when the entity is saved. After saving, the entity's id field is updated with this value.
public interface UserRepository extends JpaRepository<User, Long> {
@Query("?1")
List<User> findByLastName();
}JPQL queries use entity class names and their fields. Option A correctly uses 'SELECT u FROM User u WHERE u.lastName = 'Smith''.
@Service public class UserService { @Autowired private UserRepository userRepository; @Transactional public void createUser(String name) { User user = new User(); user.setName(name); userRepository.save(user); if (true) { throw new RuntimeException("Fail"); } } }
The @Transactional annotation rolls back the entire transaction if a RuntimeException occurs, so the save is undone.
LazyInitializationException occurs when JPA tries to load a lazy collection but the session (transaction) is closed. The collection was not loaded eagerly, so it cannot be accessed outside the transaction.