Sobes.tech
Junior — Middle

What methods and tools do you usually use to interact with a database in Spring applications?

sobes.tech AI

Answer from AI

In Spring applications, the following methods and tools are commonly used for database interaction:

  • Spring JDBC Template — simplifies working with JDBC, handles exceptions and resource release.
  • Spring Data JPA — an abstraction over JPA, allows working with repositories, supports creating queries by method names.
  • Hibernate — a popular ORM framework, often used as a JPA provider.
  • EntityManager — for working directly with JPA.
  • Spring Transaction Management — managing transactions via annotations (@Transactional).

Example of using Spring Data JPA:

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByLastName(String lastName);
}

This makes it easy to perform CRUD operations and write queries without explicit SQL.

For complex queries, @Query with JPQL or native SQL can also be used.

For testing, H2 in-memory database and Spring TestContext Framework are often employed.