在每 100 行 10 000 行上使用 flush() 方法会降低事务速度
我有一个示例项目,使用一个表和一个表。spring-boot
spring-data-jpa
postgres db
我正在尝试将循环中的 10 000 条记录放入表中并测量执行时间 - 为每 100 条记录启用或禁用类中的方法。INSERT
flush()
EntityManager
预期的结果是,启用方法的执行时间比禁用方法的执行时间短得多,但实际上我有相反的结果。flush()
用户服务.java
package sample.data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
public User save(User user) {
return userRepository.save(user);
}
}
用户存储库.java
package sample.data;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> { }
应用.java
package sample;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Transactional;
import sample.data.User;
import sample.data.UserService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@SpringBootApplication
@EnableJpaRepositories(considerNestedRepositories = true)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Autowired
private UserService userService;
@PersistenceContext
EntityManager entityManager;
@Bean
public CommandLineRunner addUsers() {
return new CommandLineRunner() {
@Transactional
public void run(String... args) throws Exception {
long incoming = System.currentTimeMillis();
for (int i = 1; i <= 10000; i++) {
userService.save(new User("name_" + i));
if (i % 100 == 0) {
entityManager.flush();
entityManager.clear();
}
}
entityManager.close();
System.out.println("Time: " + (System.currentTimeMillis() - incoming));
}
};
}
}