Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System design to support database connectivity

I am trying to develop a forum system as a part of a university assignment, which contains a database connectivity part. I am writing the server in java and decided to use hibernate as an ORM tool to save and load from the data base. My question is not about the syntax, but about the design of the entire system regarding the database.

  1. Who should be in charge of creating a session and commit transactions? should I make a singleton which recive an object and save it to the database and use this singelton in every setter/constructor of the different classes?
  2. should each change in a memory object be commited directly or should I commit only every few changes? (and if so what is the best way to do this?)
like image 364
Shperb Avatar asked Jul 11 '26 04:07

Shperb


1 Answers

Ideally, a framework should do that for you. Using Spring, for example, you could simply mark methods of Spring beans transactional using an annotation, and the session and transaction handling would be done by Spring:

@Autowired
private SessionFactory sessionFactory;

@Transactional
public void foo() {
    Session session = sessionFactory.getCurrentSession();
    // do some work with the session
}

instead of

private SessionFactory sessionFactory;

public void foo() {
    Session sess = sessionFactory.openSession();
    Transaction tx = null;
    try {
        tx = sess.beginTransaction();

        // do some  with the session

        tx.commit();
    }
    catch (RuntimeException e) {
        if (tx != null) {
            tx.rollback();
        }
        throw e; 
    }
    finally {
        sess.close();
    }
}

You should neither commit after each change, nor commit every few changes. You should commit atomic, coherent changes. That's the whole point of transactions:being able to go from a coherent state of your database to another coherent state of your database.

For example If posting a message to a topic forum consists in

  • persisting a message instance
  • incrementing the messageCount field of the forum
  • creating a notification for the topic poster

then these three changes should be in a single transaction, to make sure you don't end up with the message being persisted, but the messageCount not being incremented.

like image 159
JB Nizet Avatar answered Jul 13 '26 22:07

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!