在每个模型的不同 DAL 类 中实现 JPA 存储库方法时如何避免代码重复 lines/blocks

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

假设我有两个模型,对于每个模型,我都有一个 JPA 存储库接口,如下所示:

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

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

然后我想为每个可以使用 ORM 方法进行 CRUD 的模型创建一个 DAL class。 示例:

@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();
    }
}

然后在启动 Sonarqube 分析我的代码时出现问题,因为肯定地,Sonarqube 看到在两个 getAll() 方法中我使用同一行来获取特定模型的所有对象。 所以我的问题是这个 Sonarqube 问题的解决方案是什么?

遵循变量的命名约定。变量名可以是代表性名词,不能是一般词。在您的情况下,更改如下:

@Autowired
ICountryRepository countryRepository; // or countryRepo

 @Autowired
 IPersonRepository personRepository; // or personRepo

如果您确实有重复代码,请将其复制到接口或超级 class 和 extend/implement 使用继承的父级。