题主的目的:一个线程插入大批量的数据,和多个线程同时插入大批量的数据,在时间上是否有差距,所以在线程里用正常的orm方式操作数据库;
他想用Spring-Data-Jpa这种方式去插入数据,简化操作。
看着像SpringBoot应用。举个例子
@AllArgsConstructor
public class Task implements Callable {
private String name;
private BrandRepository brandRepository;
@Override
public String call() throws Exception {
long temp = System.currentTimeMillis();
for (int i = 1; i < 10; i++) {
brandRepository.save(new Brand(name, i));
}
return name + "执行耗时" + (System.currentTimeMillis() - temp);
}
}
BrandRepository
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Brand {
private String name;
private int seq;
}
/**
* @author Richard_yyf
* @version 1.0 2019/10/11
*/
// 把这个 Component 类比 Repository
@Component
public class BrandRepository {
public void save(Brand brand) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行插入数据库操作 " + brand.toString());
}
}
main方法
@SpringBootApplication
@Slf4j
public class Demo999Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Demo999Application.class, args);
//System.in.read(); // press any key to exit
ExecutorService executor = Executors.newCachedThreadPool();
try {
List> list = new ArrayList<>();
list.add(new Task("线程1", context.getBean(BrandRepository.class)));
list.add(new Task("线程2", context.getBean(BrandRepository.class)));
List> futures = executor.invokeAll(list);
for (Future future : futures) {
System.out.println("任务执行完成:" + future.get());
}
} catch (InterruptedException | ExecutionException e) {
log.error("", e);
}
try {
executor.shutdown();
if(!executor.awaitTermination(10000, TimeUnit.MILLISECONDS)){
// 超时的时候向线程池中所有的线程发出中断(interrupted)。
executor.shutdownNow();
}
} catch (InterruptedException e) {
// awaitTermination方法被中断的时候也中止线程池中全部的线程的执行。
System.out.println("awaitTermination interrupted: " + e);
executor.shutdownNow();
}
}
}
如果是Spring的话同理,用个java configuration类配置或者扫描相关的Bean,然后main方法里用new ***ApplicationContext()启动容器,如上操作即可。