我有一个需求,为了报告的目的,我需要执行一组带有多个联接的随机复杂查询。因此,我计划直接使用实体管理器原生查询功能。我刚试过了,看起来很管用。
@Service
public class SampleService {
@Autowired
private EntityManager entityManager;
public List<Object[]> execute(String sql){
Query query = entityManager.createNativeQuery(sql);
return query.getResultList();
}
}此代码每30秒调用一次。单线程调度进程。
问题:
发布于 2019-08-20 15:59:50
我应该使用实体管理器还是实体管理器工厂? Injecting EntityManager Vs. EntityManagerFactory
在这种情况下,EntityManager看起来很好。
我应该关闭这里的连接吗?或者它是自动管理的?不,我不认为你需要作为经理处理这件事。
如何减少DB连接池?因为它不是多线程应用程序,或者我不应该担心吗?
我怀疑您是否需要关注连接池,除非您期望大量的数据,并且您的应用程序在负载下运行缓慢。尝试做一些板凳标记,你可能有比你需要的更多的能力,并过早地优化你的应用程序。更有可能的是你会增加它的连接数,而不是减少。若要增加连接的数量,请在application.properties (或application.yml)中这样做。
还有其他建议吗!?
与一般方法不同,我会考虑在服务之外拥有一个单独的存储库类,并让这个存储库方法做一些特定的事情。使方法返回特定的结果或事物,而不是传入任何sql。
作为两个独立类(文件)的大致轮廓,如下所示
@Service
public class SampleService {
@Autowired
private MyAuthorNativeRepository myAuthorNaviveRepository;
public List<Author> getAuthors(){
return myAuthorRepository.getAuthors();
}
}
@Service
public class MyAuthorNativeRepository {
@Autowired
private EntityManager entityManager;
public List<Author> getAuthors(){
Query q = entityManager.createNativeQuery("SELECT blah blah FROM Author");
List<Author> authors = new ArrayList();
for (Object[] row : q.getResultList()) {
Author author = new Author();
author.setName(row[0]);
authors.add(author);
}
return authors;
}
}https://stackoverflow.com/questions/57574902
复制相似问题