我正在了解@Transactional,想问一个问题。为什么在以下方法中使用@Transactional很重要?
@Repository
public class CustomerDAOImpl implements CustomerDAO {
// need to inject the session factory
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional
public List<Customer> getCustomers() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query ... sort by last name
Query<Customer> theQuery =
currentSession.createQuery("from Customer order by lastName",
Customer.class);
// execute query and get result list
List<Customer> customers = theQuery.getResultList();
// return the results
return customers;
}
@Override
@Transactional
public void saveCustomer(Customer theCustomer) {
// get current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// save/upate the customer ... finally LOL
currentSession.saveOrUpdate(theCustomer);
}
@Override
@Transactional
public Customer getCustomer(int theId) {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// now retrieve/read from database using the primary key
Customer theCustomer = currentSession.get(Customer.class, theId);
return theCustomer;
}
@Override
@Transactional
public void deleteCustomer(int theId) {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// delete object with primary key
Query theQuery =
currentSession.createQuery("delete from Customer where id=:customerId");
theQuery.setParameter("customerId", theId);
theQuery.executeUpdate();
}
}
我认为在数据库上进行2次或更多次写操作时,需要使用@Transactional
。例如,如果我们要从用户A向用户B转移$ 100。在这种情况下,我们需要做两件事,首先我们需要从用户A减少$ 100,其次我们需要向用户B增加$ 100。 2作为单个原子操作进行写入。而且我了解在这种情况下为什么需要@Transactional
。
但是我不明白的是,为什么对于以上代码中的4种方法我们需要@Transactional
。在getCustomers()方法中,我们仅检索客户,在saveCustomer()中,我们仅将客户保存在数据库中,deleteCustomer()我们仅删除客户。因此,在这些方法中,数据库中只有一个写入。那为什么我们需要@Transactional
?谢谢!