【发布时间】:2021-01-26 17:09:18
【问题描述】:
我正在处理遗留代码库,并在我们的自定义存储库中看到了一些令人不安的东西。 EntityManager 直接自动连接到存储库中。例如:
@Repository
public class OperationRepository {
// Yikes
private final EntityManager entityManager;
private QOperation operation = QOperation.operation;
@Autowired
public OperationRepositoryImpl(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public Optional<Operation> findOneByIdAndType(Long operationId, OperationType type) {
JPAQuery<Operation> query = new JPAQuery<>(entityManager);
QOperation qOperation = QOperation.operation;
query.select(operation).from(operation)
.where(
operation.type.eq(type),
...
}
}
我的理解是这很危险,因为EntityManager 不是线程安全的,并且在这里作为一个字段进行管理。我在我们的任何配置文件中都没有看到明确的定义来提供EntityManager bean,所以我不确定 Spring 在这种情况下会做什么。
我将开始修复在此处使用 @PersistenceContext 的问题,但我想了解这么长时间在生产中对它的影响以及它可能带来的后果。
我们是否会将连接池大小限制为存储库 bean 中单个实体管理器的数量?是否还有其他可能造成的危险?还是我做的太多了?
【问题讨论】:
标签: java spring dependency-injection spring-data-jpa thread-safety