简体   繁体   中英

How to handle read transaction in Java to provide consistency?

I am developing a client in Java . It communicates with the server via actions. Actions are social-like actions (an example of a action is a user views the profile of another user).

With the View Profile example above, the client executes 4 queries to get the data from the database server. To provide consistency, I want to put the 4 queries in a transaction. So in my View Profile function, first I put conn.setAutoCommit(false) , then queries the data, and at the end before return I set auto commit to true again conn.setAutoCommit(true) (see the code snippet below).

try {
  // set auto commit to false to manually handle transaction
  conn.setAutoCommit(false);

  // execute query 1 
  // ...

  // execute query 2
  // ...

  // execute query 3
  // ...

  // execute query 4
  // ...

  // set auto commit to true again to not affect other actions
  conn.setAutoCommit(true);
} catch (SQLException e) {
  e.printStackTrace(System.out);
} finally {
  try {
    conn.close();
  } catch (SQLException e) {
    e.printStackTrace(System.out);
  }
}

However, when I run the code, sometimes I notice that the data returned from this action is not consistent. When I tries to combine the 4 queries in a single query, I can achieve consistency.

My question is, does setting autoCommit in Java really work with read transaction like in my example, when I want to issue separate queries to the DBMS? If not, how can I provide consistency if I want to query the DBMS in 4 separate queries?

FYI, the database server I use is Oracle DB.

For oracle, selects never do dirty reads, so are always implicitly TRANSACTION_READ_COMMITTED. If you ate ingesting data at a high rate, my guess is that data is changing between the first and last select, so your best bet would be to combine the selects into one using 3 UNIONs.

See http://www.oracle.com/technetwork/issue-archive/2005/05-nov/o65asktom-082389.html

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