Simplify CRUD with Spring Data JPA: From Setup to Unit Tests
This article explains how Spring Data JPA streamlines CRUD operations in Spring Boot by configuring dependencies, defining entity classes and repository interfaces, leveraging method‑name query derivation and @Query annotations, and validating functionality with comprehensive unit tests.
In the first article of the data‑access chapter we introduced using JdbcTemplate for basic CRUD operations. Combining it with the web module enables simple backend applications, but repetitive CRUD code quickly becomes cumbersome.
Frameworks like Hibernate map Java entities to database tables, yet developers still need to create many DAO interfaces and implementations.
Spring Data JPA eliminates most of this boilerplate: by extending JpaRepository you obtain full CRUD support without writing any implementation code.
public interface UserRepository extends JpaRepository<User, Long> {
User findByName(String name);
User findUser(@Param("name") String name);
}Configuration steps
Add the Spring Data JPA starter to pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>Configure the datasource and hibernate.hbm2ddl.auto property in application.properties (or application.yml) to control schema creation: create: drop and recreate tables on each startup. create-drop: create tables on startup and drop them on shutdown. update: create missing tables and update schema without losing data. validate: only validate the schema against the entities.
Define an entity class:
@Entity
@Data
@NoArgsConstructor
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
}Create a repository interface extending JpaRepository:
public interface UserRepository extends JpaRepository<User, Long> {
User findByName(String name);
User findByNameAndAge(String name, Integer age);
@Query("from User u where u.name=:name")
User findUser(@Param("name") String name);
}Spring Data JPA derives queries from method names (e.g., findByName, findByNameAndAge) and also supports custom JPQL via @Query.
Unit testing
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private UserRepository userRepository;
@Test
public void test() throws Exception {
// create 10 records
userRepository.save(new User("AAA", 10));
// ... other records omitted for brevity ...
userRepository.save(new User("JJJ", 100));
// verify CRUD operations
Assert.assertEquals(10, userRepository.findAll().size());
Assert.assertEquals(60, userRepository.findByName("FFF").getAge().longValue());
// delete and verify
userRepository.delete(userRepository.findByName("AAA"));
Assert.assertEquals(9, userRepository.findAll().size());
}
}Spring Data JPA is part of the broader Spring Data umbrella, offering similar abstractions for other stores such as Redis, MongoDB, and Elasticsearch.
Source code for the examples is available in the chapter3-4 directory of the GitHub repository https://github.com/dyc87112/SpringBoot-Learning/ and the Gitee mirror.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
