hibernate 存储库中扩展抽象类的实体的一种方法

wj8zmpe1  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(140)

我对抽象类作为实体是新手,所以为了训练,我创建了抽象类

@Entity
@Inheritance(strategy = TABLE_PER_CLASS)
@Getter
@Setter
@NoArgsConstructor
public abstract class ShapeEntity {
     @Id
     @GeneratedValue(generator = "system-uuid")
     @GenericGenerator(name = "system-uuid", strategy = "uuid")
     private String id = UUID.randomUUID().toString();
}

以及扩展和塑造的类:

public class SquareEntity extends ShapeEntity {
    ...
}
public class CircleEntity extends ShapeEntity {
    ...
}

每个实体都有这样的存储库:

public interface CircleEntityRepository extends JpaRepository<CircleEntity, String> {
}

当我想要更新实体时,我在每个存储库中搜索它,接下来(如果找到实体)Map参数,最后必须将该实体保存在数据库中。我如何才能轻松决定应该使用哪个存储库呢?我使用If Else创建了方法SAVE,现在可以使用:

public ShapeEntity save(ShapeEntity shapeEntity) {
    if (shapeEntity.getClass().getName().contains("CircleEntity")) {
        return circleEntityRepository.save((CircleEntity) shapeEntity);
    } else if (shapeEntity.getClass().getName().contains("SquareEntity")) {
        return squareEntityRepository.save((SquareEntity) shapeEntity);
    } else {
        throw new EntityNotFoundException();
    }
}

但这有点不舒服,因为当我有20个实体时,我将不得不创建另外20个IF循环。我可以为这个或那样做任何界面吗?

cgvd09ve

cgvd09ve1#

如果为ShapeEntity类创建了ShapeEntityRepository,则不需要if-Else块。

public interface ShapeEntityRepository
        extends JpaRepository<ShapeEntity, String>, 
        JpaSpecificationExecutor<ShapeEntity> {}

ShapeEntityRepository可用于从ShapeEntity类扩展的所有类。

ShapeEntity circleEntity = new CircleEntity();
ShapeEntity squareEntity = new SquareEntity();

shapeEntityRepository.save(circleEntity);
shapeEntityRepository.save(squareEntity);

或者,如果必须有不同的存储库,您可以使用SpringGenericTypeResolver来获取类的存储库。

@Component
public class RepositoryHolder {

    private final List<JpaRepository> jpaRepositories;

    public RepositoryHolder(List<JpaRepository> jpaRepositories) {
        this.jpaRepositories = jpaRepositories;
    }

    public JpaRepository getRepositoryBy(Class<?> domainClass) {
        Optional<JpaRepository> optionalRepository = jpaRepositories.stream()
                .filter(repository -> GenericTypeResolver
                        .resolveTypeArguments(
                                repository.getClass(),
                                Repository.class
                        )[0]
                        .equals(domainClass))
                .findFirst();
        if (optionalRepository.isPresent()) {
            return optionalRepository.get();
        } else throw new IllegalArgumentException();
    }
}

如果您想使用它,您的save(...)方法将如下所示:

public void save(ShapeEntity shapeEntity) {
    JpaRepository repository = repositoryHolder
            .getRepositoryBy(shapeEntity.getClass());
    repository.save(shapeEntity);
}

注意:JPA Repository允许使用默认的CRUD功能,您可以添加一个中间存储库Bean like here并将这些代码减少到该中间存储库。

相关问题