简体   繁体   English

什么时候在 java 中打开 DB 连接

[英]When is a DB connection is opened in java

in spring, let method A with @transitional annotation don't call DAO and execute any SQL query.在 spring 中,让带有 @transitional 注释的方法 A 不调用 DAO 并执行任何 SQL 查询。 then, method A never take a db connection?那么,方法A从不连接数据库吗?

The @Transactional annotation doesn't cause a database connection to be established, because it wouldn't know which database to connect to. @Transactional注释不会导致建立数据库连接,因为它不知道要连接到哪个数据库。

Remember, a program might connect to more than one database.请记住,一个程序可能连接到多个数据库。

When is a DB connection is opened in java?什么时候在 java 中打开 DB 连接?

That is really a broad question.这确实是一个广泛的问题。
The answer depends on the way which the application code configured the connection to the DB.答案取决于应用程序代码配置与数据库连接的方式。
Generally for "real" applications, you don't open a connection for each client request.通常对于“真实”应用程序,您不会为每个客户端请求打开连接。
It would be inefficient.这将是低效的。
Instead, when the application starts, a component called connection pool creates a specific number of connections while that number can increase, decrease according to the actual client requests.相反,当应用程序启动时,称为连接池的组件会创建特定数量的连接,而该数量可以根据实际客户端请求增加或减少。 And these connections are stored in memory.而这些连接存储在 memory 中。 At last when the client code requests a connection, the pool provides it.最后,当客户端代码请求连接时,池提供它。

About the database transaction, represented in spring by @Transactional is a different thing.关于数据库事务,在 spring 中由@Transactional表示是另一回事。 It symbolizes a unit of work performed within a database management system .它象征着在数据库管理系统中执行的一个工作单元

About:关于:

let method A with @transitional annotation don't call DAO and execute any SQL query.让带有 @transitional 注释的方法 A 不调用 DAO 并执行任何 SQL 查询。 then, method A never take a db connection?那么,方法A从不连接数据库吗?

Even without @Transactional a query needs a connection to be executed.即使没有@Transactional ,查询也需要执行连接。
If a code don't perform any query, there is few risk that it borrows a connection to the pool.如果代码不执行任何查询,它借用连接池的风险很小。

The answer is method A will not take a DB connection.答案是方法A不会建立数据库连接。

Assuming that you are using spring boot with spring data JPA.假设您使用 spring 引导和 spring 数据 JPA。

With default configuration ( spring.jpa.open-in-view is set to true), each request will be bound with a Hibernate Session object, and database access is processed with the help of the object. With default configuration ( spring.jpa.open-in-view is set to true), each request will be bound with a Hibernate Session object, and database access is processed with the help of the object.

If there is database access happens, the session object will borrow database connection from the connection pool, which was initialized in the starting phase of the application, and it will do nothing if there isn't that thing happen.如果有数据库访问发生,session object 将从应用程序启动阶段初始化的连接池中借用数据库连接,如果没有发生则什么也不做。

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

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