Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases

Matthew Francis
Matthew Francis
6,967 Points

Usage of transactions?

I've read that a big part of SQL are transactions or ACID. I'm unsure on how they play to be important, could someone give me an example showing the importance of it?

3 Answers

Chris Adamson
Chris Adamson
132,143 Points

Database transactions are important, you either want the whole set of updates to happen or none of them. As an example, if you are transferring money from one account to another. One account needs to be debited and the other credited, and both changes need to happen for the transaction to be correct.

Fahad Mutair
Fahad Mutair
10,359 Points

hi Matthew Francis , we used transaction with our code in java as shown in my code below

 @Override
    public void save(Category category) {
        // Open a session
        Session session = sessionFactory.openSession();

        // Begin a transaction
        session.beginTransaction();

        // Save the category
        session.saveOrUpdate(category);

        // Commit the transaction
        session.getTransaction().commit();

        // Close the session
        session.close();
    }
Seth Kroger
Seth Kroger
56,413 Points

Sometimes in a database a set of changes need to happen as a single unit. A good example of this would be a bank transaction between two accounts. You want the withdrawal from one account to happen along with the deposit to the other but don't want other things to happen to the account to happen in the middle, like another withdraw from the first account leaving insufficient funds, or an error in updating the second causing the money to vanish. This is where transactions come in. They allow you to create a set of changes to happen as one, and the changes aren't actually made until you are finished and ready to commit them.