简体   繁体   English

Spring JPA:如何在一轮中运行多SQL查询?

[英]Spring JPA: How to run multi sql query in one round?

In spring if we define method in repository like this: findByName(String name) , we could call this method to retrieve data back. 在春季,如果我们在存储库中这样定义方法: findByName(String name) ,我们可以调用该方法来取回数据。 What I want is that, could I have some ways to call 2 or more methods like I say above, and spring sends query to database in just one round instead of 2rounds? 我想要的是,我可以像上面所说的那样,有一些方法来调用2个或更多方法,并且spring仅在一轮而不是2轮内将查询发送到数据库吗? I would like to optimize performance in the case that I am certain that some sql queries will be sent togother 在我确定某些sql查询将发送给其他人的情况下,我想优化性能

update: one round means in one connection we send multi sql queries. 更新:一轮意味着在一个连接中,我们发送多个sql查询。 The object is to avoid more than one round trip time when there is more than 1 sql query is about to send. 目的是当要发送的SQL查询数量超过1个时,避免往返时间超过一个。 eg, query 1 is select * from table where xx=bb 例如,查询1是从xx = bb的表中选择*

query 2 is selext * from another_table where zz=cc 查询2是selext *来自another_table,其中zz = cc

in trivial way, we may send 2 queries like this: 1. send query 1 by calling repository's findbyxx method 2. send query 2 by calling repository's findbyzz method 以平凡的方式,我们可能会像这样发送2个查询:1.通过调用存储库的findbyxx方法发送查询1 2.通过调用存储库的findbyzz方法发送查询2

in above case, query 2 will be sent after query 1's response came back. 在上述情况下,查询2将在查询1的响应返回后发送。 This is a waste IMHW. 这是浪费的IMHW。 I am seeking a way to send these 2 queries at once and got answer at once. 我正在寻找一种方法来一次发送这两个查询并立即得到答案。

If you want to keep the database connection between these two queries, you must set up a transaction manager for your JPA Configuration: 如果要在这两个查询之间保持数据库连接,则必须为“ JPA配置”设置事务管理器:

<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
   <property name="entityManagerFactory" ref="yourEntityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />

This will imply that when you annotate a @Service 's method with @Transaction (or the whole class), the same session/connection will be kept between your queries. 这意味着当您使用@Transaction (或整个类)注释@Service的方法时,查询之间将保持相同的会话/连接。

For more info: https://www.baeldung.com/transaction-configuration-with-jpa-and-spring 有关更多信息: https : //www.baeldung.com/transaction-configuration-with-jpa-and-spring

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM