Search code examples
javaspringspring-data-jpasonarqubedata-access-layer

How to avoid duplicate lines/blocks of code when implementing JPA repository methods in different DAL classes for every model


Let's say I have two models and for every model, I have a JPA repository interface like so:

public interface IPersonJPARepository extends JpaRepository<Person, Long> {
.....
}

public interface ICountryJPARepository extends JpaRepository<Country, Long> {
.....
}

Then I would like to have a DAL class for every model where I can use ORM methods for CRUD. Example:

@Repository
public class PersonDal implements IPersonDal {
    @Autowired
    IPersonRepository repo;

    @Override
    public List<Person> getAll() {
        return repo.findAll();
    }
}

@Repository
public class CountryDal implements ICountryDal {
    @Autowired
    ICountryRepository repo;

    @Override
    public List<Country> getAll() {
        return repo.findAll();
    }
}

Then the problem occurred when starting Sonarqube to analyze my code because definitely, Sonarqube sees that in both getAll() methods I am using the same line to get all the objects for a specific model. So my question is what is the solution for this Sonarqube problem?


Solution

  • Follow Naming Convention for variables. The variable names can be representative nouns and not general words. In your case, change like below:

    @Autowired
    ICountryRepository countryRepository; // or countryRepo
    

    And

     @Autowired
     IPersonRepository personRepository; // or personRepo
    

    And if you really have a dupicate code, copy it to a an interface or a super class and extend/implement the parent using inheritance.