In JDBC can we say the transaction begins as soon as we get the connecti开发者_如何学Goon and finishes as we close the connection. IS this right? If yes can we say In different requests sharing the same connection, even all the uncommitted transactions will be visible to all all requests?
@BalusC - This is not correct really. By default autocommit is set to true, which means that transaction begins before any JDBC operation and finishes RIGHT AFTER that single operation - not when connection is closed.
But you are right that sharing connection is indeed not good, If you want to multi-thread your DB it's best to handle it in the way that you have thread pool (look for ThreadPoolExecutor in java.util.concurrent) and for each thread you get a separate connection. ConnectionPool is also a good one, but I would rather limit that through ThreadPool - this way there is never a thread waiting for a connection from the pool.
That's right. That's the default behaviour. You can take over this control by setting the auto commit to false
by connection.setAutoCommit(false)
after retrieving the connection and committing the transaction by connection.commit()
after doing all queries.
However, sharing a connection between different requests (threads) is at its own already a bad design. Your application is this way not threadsafe. You do not want to share the same connection among different threads. If all you want is eliminating the cost of connecting a database, then you should consider using a connection pool.
first rule when you access the database. Every nontransactional operation should:
1.open connection, if have connection pool then get connection from the pool 2. Create execute statement 3. if is read query then map the result set. 4. close the result set. 5. close the statement. 6. close the connection.
if you want your operation to be in transaction then you should consider this approach:
Operation 1: 1. getSharedConnection 2.create/execute statement 3. if is read query then map the result set. 4. close resultSEt 5. close statement
operation 2: Same as operation 1.
and the transaction:
public void updateInTransaction(){ Connection conn=pool.getConnection();//or you can create a new connection conn.setAutocommit(false); operation1(conn); operation2(conn); conn.close; }
This is just basics for small applications. If you are developing bigger applicatoin you should using same framework like JDBCTemplates from Springsoruce.
精彩评论