4.1 Transactions and database integrity

The normal mode of operation of a database is when it receives thousands of requests every minute from hundreds of different clients. In this case, situations often arise when the same data is accessed from different queries.

Less often, but, again, from time to time there are situations when one request reads a certain line, and another request changes it at the same time. Imagine what happens if someone reads a line that is only half changed? Nothing good.

This problem is solved in several ways. First, you can just lock the line that changes. Both for reading and for writing. This method works, but the speed of the base suffers greatly.

The second way is to lock the string for writing only. However, there will still be a problem when someone tries to read the partially modified line. Conclusion - there should not be a situation when the line is partially changed.

Therefore, they came up with a third method - transactions. A transaction is a group of actions that are performed either all together, or none at all. There cannot be a situation where part of the actions were performed, and the second part was not. If it is not possible to make all the changes, then all the changes already made are rolled back.

Any modern SQL server allows you to change data only in transactions. You open a transaction, make any changes to any number of tables, and commit the transaction. SQL Server then tries to make changes. If everything is just fine, then they will be added to the general database. If there were problems, then all changes will be canceled.

Hibernate also uses this paradigm. That is why in the previous lecture we saw that when trying to save the Employee object to the database, a transaction was first opened, and after saving, it was committed.

We will go into this topic in more detail, but for now, just know why transactions are needed and where they are usually used.

4.2 Getting objects

If Hibernate executes a request to get data, then there is no need to explicitly open a transaction. Hibernate itself will do this if it sees fit: it has its settings, as well as the settings of the SQL server.

We will analyze how to work with the database. And the simplest of them is getting an object by its ID . To do this, use the method get()on the session object . The general form of such a request:

Class Name = session.get(Class.class, ID);

Example:

public User getUserById(Integer id) {
    try (Session session = sessionFactory.openSession()) {
        User user = session.get(User.class, id);
        return user;
    }
}

4.3 Saving (adding) objects

If you want to save your object to the database, then a query will be executed at the SQL levelINSERT. Therefore, your actions must be performed as a separate transaction. Also, it's better to use the sessionpersist() object's method for persistence .

The general form of such a request:

session.persist(An object);

The method persist()changes not only the base, but also the object itself. The thing is that when we add an object to the database, this object does not yet have its own ID before adding it . Well, usually so, although there are nuances. And after adding the object already has an ID .

public boolean saveUser(User user) {
    try (Session session = sessionFactory.openSession()) {
            Transaction transaction = session.beginTransaction();
            session.persist(user);
            transaction.commit();
            return true;
    }
    catch() {
    return false;
   	}
}

The Session object also has a method save()that performs a similar function. It's just that the method save()is the old Hibernate standard and the method persist()is the JPA standard.

4.4 Deleting objects

If you want to delete an existing object, then it is very easy to do so. To do this, the session object has a special method - remove().

The general form of such a request:

session.remove(An object);

And, of course, let's write the code with an example:

public boolean removeUser(User user) {
    try (Session session = sessionFactory.openSession()) {
            Transaction transaction = session.beginTransaction();
            session.remove(user);
            transaction.commit();
            return true;
    }
    catch() {
    return false;
   	}
}

Why is it so difficult, you ask?

Well, first of all, any changes to the database always have different and not always obvious consequences. And secondly, this object could have child objects associated with it, etc. So deletion scenarios are often non-trivial.

undefined
1
Task
Module 4. Working with databases, level 9, lesson 3
Locked
task0905
task0905