Sobes.tech
Junior — Middle

Have you had experience using transaction operators when working with databases?

sobes.tech AI

Answer from AI

Yes, I have experience using transaction operators in Java when working with databases, particularly through JDBC and Spring.

In JDBC, transactions are managed manually using methods like setAutoCommit(false), commit(), and rollback(). Example:

Connection conn = null;
try {
    conn = dataSource.getConnection();
    conn.setAutoCommit(false); // start transaction

    // perform multiple operations
    PreparedStatement ps1 = conn.prepareStatement("INSERT INTO users(name) VALUES (?)");
    ps1.setString(1, "Ivan");
    ps1.executeUpdate();

    PreparedStatement ps2 = conn.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE user_id = ?");
    ps2.setBigDecimal(1, new BigDecimal("100.00"));
    ps2.setInt(2, 1);
    ps2.executeUpdate();

    conn.commit(); // commit transaction
} catch (SQLException e) {
    if (conn != null) {
        conn.rollback(); // rollback on error
    }
    throw e;
} finally {
    if (conn != null) {
        conn.setAutoCommit(true);
        conn.close();
    }
}

In Spring Framework, transaction management is usually handled with the @Transactional annotation, which simplifies work and automatically manages commit/rollback:

@Service
public class UserService {

    @Transactional
    public void transferMoney(int fromUserId, int toUserId, BigDecimal amount) {
        // database operations that will be executed within a single transaction
    }
}

This approach avoids manual transaction management and reduces the likelihood of errors.

Have you had experience using transaction operators… - sobes.tech