Spring JPA事務(wù)管理與自定義操作實(shí)例解析(最新推薦)
在Spring框架中,數(shù)據(jù)持久化操作常常與事務(wù)管理緊密相關(guān)。本文將深入探討Spring Data JPA中的事務(wù)管理機(jī)制,并結(jié)合具體實(shí)例,展示如何自定義事務(wù)行為以滿足不同的業(yè)務(wù)需求。
Spring JPA中的事務(wù)管理
在Spring Data JPA中,默認(rèn)的CrudRepository
實(shí)現(xiàn)是SimpleJpaRepository
。這個(gè)類通過@Transactional
注解支持事務(wù)管理,其中readOnly = true
屬性意味著默認(rèn)情況下所有方法都在只讀事務(wù)中執(zhí)行。對(duì)于寫操作,如deleteById
,deleteAll
等,它們通過@Transactional
注解覆蓋了只讀行為,使得這些方法在寫事務(wù)中執(zhí)行。
@Repository @Transactional(readOnly = true) public class SimpleJpaRepository<T, ID> implements JpaRepository<T, ID>, JpaSpecificationExecutor<T> { @Transactional public void deleteById(ID id) {...} // 其他寫操作 }
自定義Repository事務(wù)行為
若要自定義事務(wù)設(shè)置,我們可以重寫特定的方法,并添加@Transactional
注解。例如,我們可以為deleteById
方法設(shè)置一個(gè)超時(shí)時(shí)間:
public interface EmployeeRepository extends CrudRepository<Employee, Long> { @Transactional(timeout = 10) @Override public void deleteById(ID id); }
在Repository外部使用事務(wù)
在Repository外部使用事務(wù),需要在配置類上添加@EnableTransactionManagement
注解:
@Configuration @ComponentScan @EnableTransactionManagement public class AppConfig { // ... }
然后,我們可以在服務(wù)類中使用@Transactional
注解來管理事務(wù):
@Service public class MyExampleBean{ @Transactional public void saveChanges() { repo.save(..); repo.deleteById(..); ..... } }
實(shí)例分析
Entity定義
@Entity public class Employee { @Id @GeneratedValue private Long id; @Column(unique = true) private String name; private String dept; private int salary; // 省略其他字段和方法 }
Repository定義
public interface EmployeeRepository extends CrudRepository<Employee, Long> { @Transactional(timeout = 10) @Override <S extends Employee> S save(S s); }
客戶端操作
@Component public class ExampleClient { @Autowired private EmployeeRepository repo; public void findEmployees() { System.out.println(" -- finding all employees --"); repo.findAll().forEach(System.out::println); } @Transactional public void saveEmployees() { repo.save(Employee.create("Mike", "Sale", 1000)); repo.save(Employee.create("Diana", "Admin", 3000)); repo.save(Employee.create("Diana", "IT", 3200)); // 這將觸發(fā)異常 } }
在上面的saveEmployees
方法中,我們嘗試保存具有重復(fù)名稱的員工。由于Employee
實(shí)體類中通過@Column(unique = true)
指定了唯一列,最后一個(gè)保存調(diào)用將失敗,整個(gè)事務(wù)將回滾。如果不使用@Transactional
注解,前兩名員工仍然會(huì)被保存,即整個(gè)保存過程不會(huì)是原子性的。
JavaConfig配置
@EnableJpaRepositories @ComponentScan @Configuration @EnableTransactionManagement public class AppConfig { @Bean EntityManagerFactory entityManagerFactory() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("example-unit"); return emf; } @Bean public PlatformTransactionManager transactionManager() { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(entityManagerFactory()); return txManager; } }
主類
public class ExampleMain { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); ExampleClient exampleClient = context.getBean(ExampleClient.class); try { exampleClient.saveEmployees(); } catch (Exception e) { System.err.println(e); } exampleClient.findEmployees(); EntityManagerFactory emf = context.getBean(EntityManagerFactory.class); emf.close(); } }
如果不在saveEmployees
方法上使用@Transactional
注解,那么即使觸發(fā)了唯一性約束異常,前兩名員工的數(shù)據(jù)仍然會(huì)被保存,這違背了事務(wù)的原子性原則。
通過上述分析,我們可以看到Spring JPA事務(wù)管理的靈活性和強(qiáng)大功能,以及如何通過自定義事務(wù)行為來滿足復(fù)雜的業(yè)務(wù)需求。
到此這篇關(guān)于Spring JPA事務(wù)管理與自定義操作實(shí)例解析的文章就介紹到這了,更多相關(guān)Spring JPA事務(wù)管理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java如何利用FastJSON、Gson、Jackson三種Json格式工具自定義時(shí)間序列化
本篇文章主要介紹了java如何利用FastJSON、Gson、Jackson三種Json格式工具自定義時(shí)間序列化,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08Hibernate映射解析之關(guān)聯(lián)映射詳解
所謂關(guān)聯(lián)映射就是將關(guān)聯(lián)關(guān)系映射到數(shù)據(jù)庫里,在對(duì)象模型中就是一個(gè)或多個(gè)引用。下面這篇文章詳細(xì)的給大家介紹了Hibernate映射解析之關(guān)聯(lián)映射的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-02-02SpringBoot?實(shí)現(xiàn)微信推送模板的示例代碼
這篇文章主要介紹了SpringBoot?實(shí)現(xiàn)微信推送模板,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-12-12詳解Java繼承中屬性、方法和對(duì)象的關(guān)系
這篇文章主要幫助大家詳細(xì)介紹了Java繼承中屬性、方法和對(duì)象的關(guān)系,感興趣的朋友可以參考一下2016-03-03使用dom4j解析xml文件,并轉(zhuǎn)出json格式問題
這篇文章主要介紹了使用dom4j解析xml文件,并轉(zhuǎn)出json格式問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09Java實(shí)現(xiàn)將每日新聞添加到自己博客中
這篇文章主要為大家詳細(xì)介紹了Java如何實(shí)現(xiàn)將每日新聞添加到自己博客中并發(fā)送到微信群中,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-12-12