我天真地实现了一个 Web 服务,它使用 Json 对象列表并将它们存储在 SQL 数据库中
springframework.data.jpa
(JPA 和 Hibernate)。然而,该解决方案的性能较低,并且分析器提示我主要问题在于从 Json 对象一一创建实体。
下面的代码经过简化,但基本上是:对于传入列表中的每个 Json 对象,都会创建两个实体:DataEntity 和 IdentityEntity。前者持有感兴趣的数据,将后者作为FK,有一个时间和一个人的复合PK。
我想加快存储过程。我通过探查器确定,插入每个新实体后执行的刷新操作过多。由于我需要在给定时间插入数千条记录,这会导致性能问题。我可以在一个事务中进行插入吗?或者还有其他优化方法吗?
数据类(我有很多类似的类):
@Entity
public class DataEntity {
@EmbeddedId
private IdentityEntity identity;
private Double data;
}
可嵌入实体:
@Embeddable
public class IdentityEntity implements Serializable {
@NonNull
private Long personId;
@NonNull
private Long datetimeId;
}
JPA 存储库:
@Repository
public interface DataRepository extends JpaRepository<DataEntity, IdentityEntity> {}
简化的 Controller :
public class DataController{
@Autowired
private DataRepository dataRepository;
@Autowired
private DatetimeRepository datetimeRepository;
@PostMapping("/upload")
public void upload(...List<DataJson> items) {
PersonEntity person = getPerson(...); // fast enough
for (DataJson i : items) { // begin transaction here?
saveNewEntity(i, person.getId());
}
}
private void saveNewEntity(DataJson json, Long personId) {
TimeEntity savedDatetime = datetimeRepository.save(new TimeEntity(json.getDatetime()));
IdentityEntity mi = IdentityEntity(personId, savedDatetime.getId());
DataEntity entry = new DataEntity(mi, json.getData());
dataRepository.save(entry);
}
}
<小时/>
编辑:在进一步深入研究分析器后,我发现另一个耗时的操作可能是事务管理本身。虽然我还没有实现或配置任何事务行为,但我怀疑 Spring Boot 已经为 Hibernate ORM 默认配置了一些东西。我开始认为现在在循环的每次迭代中都会创建一个事务,这是第一个性能问题,也导致了第二个问题,在事务结束时,所有内容都被刷新并写入数据库。
最佳答案
是的。 SimpleJpaRepository
中的所有方法注释为 @Transactional
.
只需添加 @Transactional
对您的上传方法进行注释。
...或
首先创建所有对象并使用save(Iterable<S> entities)
一次性保存它们方法。
关于java - 优化插入多个具有嵌入式主键的实体时的 JPA 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58712279/