Don't Forget About Data Integrity

As our frameworks like Spring, Grails, Rails become easier and easier to use and libraries like spring-data, GORM and ActiveRecord do much more of the heavy lifting we can't get lazy and forget about data integrity. As helpful and powerful as these frameworks and libraries are, they don't do everything.

Suppose you have the following data structures:

hierarchy

most examples online might provide the following service method in a Spring-Data environment as an example:

@Transactional
public Department save(Department department) {  
   return departmentRepository.save(department);
}

Here are some assumptions:

  • The database will catch any constraint violations and throw exceptions - Good
  • Our front-end code (Controller) is doing some validation before passing the Department into the service layer, possibly preventing database level exceptions being thrown - Awesome
  • DepartmentGroup and Department belong to the same Organization - Uh oh!

The last assumption is dangerous. Nothing about our database structure, service or baked in repository method prevents the following...

DepartmentGroup group = new DepartmentGroup();  
group.setOrganization(new Organization(1L)); // Organization 1  
Department department = new Department();  
department.setOrganization(new Organization(2L)); // Organization 2  
department.setDepartmentGroup(group);  
departmentService.save(department);  

...from failing. This will persist and our data will be corrupt. Adding some simple logic such as...

public Department save(Department department) throws DataIntegrityViolationException {

        if (!department.getDepartmentGroup().getBrand().equals(department.getBrand())) {
            throw new DataIntegrityViolationException("Invalid Department Group for Department");
        }

        return this.departmentRepository.save(department);
    }

...will keep our data integrity intact. There's obviously multiple ways to handle this. This is just a simple example to get the point across. And that point is simple; Don't forget about Data Integrity.