简体   繁体   中英

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. then, method A never take a db connection?

The @Transactional annotation doesn't cause a database connection to be established, because it wouldn't know which database to connect to.

Remember, a program might connect to more than one database.

When is a DB connection is opened in java?

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. 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. 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. then, method A never take a db connection?

Even without @Transactional a query needs a connection to be executed.
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.

Assuming that you are using spring boot with spring data 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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