[英]Spring hibernate transaction
文檔說我們必須先進行交易,然后再進行插入。 但是下面的代碼如何運行? 因為保存后我要調用beginTransaction()。
@Override
public void insertCustomer(Employees employee) {
Session session = sessionFactory.openSession();
session.save(employee);
session.beginTransaction();
session.getTransaction().commit();
session.close();
}
而且我對Spring的@transactional屬性(稱為propagation)還有一個疑問,該屬性可以如下配置,
@Transactional(propagation=Propagation.NEVER)
據說這是非過渡運行的。 這意味着什么?
請幫助我理解以上概念
以下代碼如何運行? 因為保存后我正在調用begintransaction。
一旦調用save()
Hibernate將不會嘗試插入/更新數據庫。 僅當您嘗試提交事務時,它才會嘗試插入。 如果您不提交事務,它將不會按預期運行。
@Transactional(propagation = Propagation.NEVER)是什么意思?
以下是Spring支持的7種不同的事務傳播行為
(注意:您不需要在所有方法中都使用事務。您也可以使用不帶事務的普通方法)
要在事務下執行方法,請使用@Transactional
對其進行注釋。 默認情況下,它在PROPAGATION_REQUIRED行為下運行,這意味着兩件事之一
當使用@Transaction(prorogation=Propagation.NEVER)
注釋方法時, 不應使用其他方法通過活動事務對其進行調用。 否則,將引發異常。
當您要嚴格執行沒有活動事務的特定邏輯/方法時,將使用Propagation.NEVER
。 根據我的經驗,我從未使用過此屬性。 您將有95%的時間對默認的PROPAGATION_REQUIRED
行為感到滿意。 但是,最好對不同的行為有所了解。
讓我用一個例子來解釋:
@Component
public class TransactionTutorial {
@Transactional
public void aboutRequired() {
//This method will create a new transaction if it is called with no active transaction
//Some logic that should be executed within a transaction
//normal() method will also run under the newly created transaction.
normal();
//An exception will be thrown at this point
//because aboutNever() is marked as Propagation.NEVER
aboutNever();
}
@Transactional(propagation=Propagation.NEVER)
public void aboutNever() {
//This method should be called without any active transaction.
//If it is called under active transaction, exception will occur.
//Some logic that should be executed without a transaction.
}
public void normal() {
//This method is not bothered about surrounding transaction.
//You can call this method with or without an active transaction.
//Some logic
}
}
閱讀上面的代碼可能會更好地理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.