【发布时间】:2020-03-01 21:10:31
【问题描述】:
我天真地实现了一个 Web 服务,它使用一个 Json 对象列表并将它们存储在 SQL 数据库中
springframework.data.jpa(JPA 和休眠)。但是,该解决方案的性能较低,分析器提示我主要问题在于从 Json 对象中逐个创建实体。
下面的代码被简化了,但基本上是:对于传入列表中的每个 Json 对象,都会创建两个实体:DataEntity 和 IdentityEntity。前者持有感兴趣的数据,后者作为FK,有一个时间和一个人的复合PK。
我想加快存储过程。我已经用探查器确定,在插入每个新实体后有太多的 flush 操作正在执行。由于我需要在给定时间插入数千条记录,这会导致性能问题。我是否可以在一个事务中进行插入,或者有哪些其他优化方法?
数据类(我有很多类似的类):
@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> {}
简化控制器:
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 配置了一些默认设置。我开始认为现在在循环的每次迭代中都会创建一个事务,这是第一个性能问题,也导致了第二个问题,在事务结束时,所有内容都被刷新并写入数据库。
【问题讨论】:
-
想解释一下否决票?
标签: java hibernate spring-boot jpa spring-data-jpa