d56
d56

Reputation: 843

How to use Spring, Hibernate, MySQL ISAM with transactions?

I am using Hibernate and Spring on a small personal project. Well, still a newbie in this area, so would like to raise some basic questions re transactions.

Many thanks

Upvotes: 0

Views: 383

Answers (3)

gkamal
gkamal

Reputation: 21000

The spring hibernate transaction manager also takes care of managing the hibernate sessions for you. If you use the sessionFactory.getCurrentSession() api along with the spring hiberanteTranasactionManager, spring will take care of opening a session when the transaction begins and closes it after the transaction ends.

This makes your code cleaner. You don't have to litter your code with openSession and closeSession. It is also a good idea to use the session per request approach instead of opening and closing session for every hibernate operation.

As you mention the right place to put this is in the service layer - classes that implement the logic for a use case by invoking a number of DAO methods. If you don't have one either you are doing multiple DAO calls from the controller or your DAOs are doing multiple db operations when required.

If you are calling multiple DAO methods from a controller method you should put @Transactional on the controller method.

If your DAOs are making multiple DB operations you should put it at the DAO level.

If the application involves non-trivial logic (over and beyond basic CRUD), it would be better to create a service layer and manager transactions at this level.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340693

Is there actually a must to use transactions?

Yes it is. One of the fundamental features of relational databases are transactions. However simple @Transactional with default parameters is enough. You can however declare transactions in XML using AOP, surrounding whole set of classes, e.g. all having *DAO name.

What is the best place to put the @Transactional attribute on?

Service layer, see: What is the right way to use spring MVC with Hibernate in DAO, sevice layer architecture.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691635

Yes, you always need to use transactions to access a database using Hibernate (and even without actually). I just wouldn't use MyISAM, since, as you said, it isn't a transactional DB engine.

The best place to put the @Transactional annotation is on your functional services, in the service layer. Either you introduce a real service layer, or you consider that the DAO layer is in fact your service layer. But beware that if your controller must save a foo using the FooDAO, and a bar using the BarDAO, and if these two insertions should be done transactionally, then you have a big problem. That's why a service layer is so important: it can access multiple DAOs in a single transaction

Upvotes: 1

Related Questions