user1153321
user1153321

Reputation: 357

In Spring 3.2, should we use @Transactional annotation for db activities?

I use spring 3.2 and Hibernate 4 in my project. When i query table i get a "No Session found for current thread" message. I try to use @Transactional annotation(it get success) but i don't want to put @Transactional to every service implementation.

Is there an another way?

In other words "How can i do a simple "insert" operation without using @Transaction?"

Thx...

Upvotes: 0

Views: 1439

Answers (2)

jax
jax

Reputation: 38643

You should not have @Transactional on you DAO methods, in fact you should never be accessing your DAO methods directly, you should be using an @Service. A service will use zero or more DAO classes to perform operations, only after all operations are completed will the transaction be committed.

@Repository
public class CustomerDao() {
    // dao methods here, they are not transactional but will be run within a sevice transaction
}

@Service
@Transactional
public class CustomerService() {

   private final CustomerDao customerDao;

   @Autowired
   public CustomerService(CustomerDao customerDao) {
       this.customerDao = customerDao;
   }

   //service methods here (they are all transactional because we have annotated the class)
}

Upvotes: 2

Rajesh
Rajesh

Reputation: 3034

@Transactional is used for making a java code call in transaction so that in case any exception occurred during the process then all database changes will be rolled back. In ideal scenario every service which you think should be independent should have @Transactional annotation. Hibernate also want each database calls in transaction thats why they have implemented in such a way that Transaction will be required for each database query to be successful. I am not sure why you wanted your service to be out of transaction still they would like to fire database calls.

Upvotes: 1

Related Questions