Back to Repositories

Testing Hierarchical Department JPA Operations in spring-boot-demo

This test suite evaluates JPA repository functionality for Department and User entities in a Spring Boot application. It focuses on testing hierarchical department structures and user-department relationships through JPA persistence operations.

Test Coverage Overview

The test suite covers CRUD operations for department management with hierarchical structures and user associations.

  • Tests department creation with multiple hierarchy levels
  • Verifies user-department relationship management
  • Validates department hierarchy persistence
  • Tests department-user bidirectional relationships

Implementation Analysis

The testing approach utilizes Spring Boot’s testing framework with JPA repositories and transaction management.

Implementation features:
  • @Transactional annotation for test data management
  • Builder pattern for entity creation
  • Hierarchical data structure testing
  • Bidirectional relationship handling between User and Department entities

Technical Details

Testing infrastructure includes:
  • JUnit test framework
  • Spring Boot Test support
  • Lombok for logging (@Slf4j)
  • Hutool JSON utilities for response validation
  • JPA repositories with @Autowired dependency injection

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Proper transaction management for test isolation
  • Comprehensive relationship testing
  • Clear test data setup and cleanup
  • Effective use of logging for test verification
  • Structured approach to testing complex hierarchical data

xkcoding/spring-boot-demo

demo-orm-jpa/src/test/java/com/xkcoding/orm/jpa/repository/DepartmentDaoTest.java

            
package com.xkcoding.orm.jpa.repository;

import cn.hutool.json.JSONUtil;
import com.xkcoding.orm.jpa.SpringBootDemoOrmJpaApplicationTests;
import com.xkcoding.orm.jpa.entity.Department;
import com.xkcoding.orm.jpa.entity.User;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONArray;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import javax.transaction.Transactional;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * jpa 测试类
 * </p>
 *
 * @author 76peter
 * @date Created in 2018-11-07 14:09
 */
@Slf4j
public class DepartmentDaoTest extends SpringBootDemoOrmJpaApplicationTests {
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private UserDao userDao;

    /**
     * 测试保存 ,根节点
     */
    @Test
    @Transactional
    public void testSave() {
        Collection<Department> departmentList = departmentDao.findDepartmentsByLevels(0);

        if (departmentList.size() == 0) {
            Department testSave1 = Department.builder().name("testSave1").orderNo(0).levels(0).superior(null).build();
            Department testSave1_1 = Department.builder().name("testSave1_1").orderNo(0).levels(1).superior(testSave1).build();
            Department testSave1_2 = Department.builder().name("testSave1_2").orderNo(0).levels(1).superior(testSave1).build();
            Department testSave1_1_1 = Department.builder().name("testSave1_1_1").orderNo(0).levels(2).superior(testSave1_1).build();
            departmentList.add(testSave1);
            departmentList.add(testSave1_1);
            departmentList.add(testSave1_2);
            departmentList.add(testSave1_1_1);
            departmentDao.saveAll(departmentList);

            Collection<Department> deptall = departmentDao.findAll();
            log.debug("【部门】= {}", JSONArray.toJSONString((List) deptall));
        }


        userDao.findById(1L).ifPresent(user -> {
            user.setName("添加部门");
            Department dept = departmentDao.findById(2L).get();
            user.setDepartmentList(departmentList);
            userDao.save(user);
        });

        log.debug("用户部门={}", JSONUtil.toJsonStr(userDao.findById(1L).get().getDepartmentList()));


        departmentDao.findById(2L).ifPresent(dept -> {
            Collection<User> userlist = dept.getUserList();
            //关联关系由user维护中间表,department userlist不会发生变化,可以增加查询方法来处理  重写getUserList方法
            log.debug("部门下用户={}", JSONUtil.toJsonStr(userlist));
        });


        userDao.findById(1L).ifPresent(user -> {
            user.setName("清空部门");
            user.setDepartmentList(null);
            userDao.save(user);
        });
        log.debug("用户部门={}", userDao.findById(1L).get().getDepartmentList());

    }

}