最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

spring?boot之使用spring?data?jpa的自定義sql方式

 更新時間:2021年12月08日 15:29:24   作者:冰霜秋月  
這篇文章主要介紹了spring?boot之使用spring?data?jpa的自定義sql方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

spring data jpa介紹

PA(Java Persistence API)是Sun官方提出的Java持久化規(guī)范。它為Java開發(fā)人員提供了一種對象/關聯(lián)映射工具來管理Java應用中的關系數據。他的出現(xiàn)主要是為了簡化現(xiàn)有的持久化開發(fā)工作和整合ORM技術,結束現(xiàn)在Hibernate,TopLink,JDO等ORM框架各自為營的局面。值得注意的是,JPA是在充分吸收了現(xiàn)有Hibernate,TopLink,JDO等ORM框架的基礎上發(fā)展而來的,具有易于使用,伸縮性強等優(yōu)點。

自定義SQL查詢

Spring data 覺大部分的SQL都可以根據方法名定義的方式來實現(xiàn),但是由于某些原因我們想使用自定義的SQL來查詢,spring data也是完美支持的;在SQL的查詢方法上面使用@Query注解,如涉及到刪除和修改在需要加上@Modifying.

    public interface CustomerRepository extends JpaRepository<Customer, Integer>{
    @Modifying
    @Query("update Customer c set c.customerName=?1 where c.id=?2")
    Integer modifyByIdAndUserId(String customerName,Integer id);
    @Modifying
    @Query("delete from Customer where id = ?1")
    void deleteByCustomerId(Integer id);
}

注意當調用自定義更新和刪除sql操作時,會出現(xiàn)下面的異常

org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:396) at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:227) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) at com.sun.proxy.$Proxy88.modifyByIdAndUserId(Unknown Source) at com.baidu.HelloPeopleApplicationTests.contextLoads(HelloPeopleApplicationTests.java:42) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73) at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206) Caused by: javax.persistence.TransactionRequiredException: Executing an update/delete query at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1496) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:380) at com.sun.proxy.$Proxy95.executeUpdate(Unknown Source) at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.doExecute(JpaQueryExecution.java:256) at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:91) at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:136) at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:125) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:590) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:578) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ... 41 more

對于該異常的原因是更新和刪除操作沒有進行事務處理,解決辦法是在service層調用CustomerRepository接口的方法的方法上添加注解@Transactional進行事務的處理,然后在調用service層的方法

@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;
    @Transactional
    public void deleteByCustomerId(Integer id) {
        customerRepository.deleteByCustomerId(id);
    }
    @Transactional
    public Integer modifyByIdAndUserId(String customerName,Integer id) {
        return customerRepository.modifyByIdAndUserId(customerName, id);
    }
Integer line = customerService.modifyByIdAndUserId("張三", 4);
        System.out.println(line);
        customerService.deleteByCustomerId(3);

執(zhí)行后如圖所示:

這里寫圖片描述

jpa兩種自定義SQL的方式

當你的抽象類繼承了JpaRepository類時,就會擁有一些基本的增刪改查操作。但是,很多時候只有這些簡單的功能是不夠的的,jpa也支持原生SQL和實體類SQL進行自定義查詢。

1. 原生SQL

@Query(value = "SELECT t2.userId, t1.title, t1.content, t1.completeTime, t2.scheduleState" +
            " FROM schedule t1 LEFT JOIN schedule_user t2 ON t1.id = t2.schedule_id " +
            " WHERE t2.user_id = ?1 AND t2.schedule_state = ?2", nativeQuery=true)
    List<ScheduleUserView> findScheduleListByState(Long userId, int scheduleState);

2. 實體類SQL

@Query(value = "SELECT new com.x3.schedule.saas.table.ScheduleUserView(" +
            " t2.userId, t1.title, t1.content, t1.completeTime, t2.scheduleState)" +
            " FROM ScheduleTable t1 LEFT JOIN ScheduleUserTable t2 ON t1.scheduleId = t2.scheduleId " +
            " WHERE t2.userId = ?1 AND t2.scheduleState = ?2")
    List<ScheduleUserView> findScheduleListByState(Long userId, int scheduleState);

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • java 實現(xiàn)MD5加密算法的簡單實例

    java 實現(xiàn)MD5加密算法的簡單實例

    這篇文章主要介紹了java 實現(xiàn)MD5加密算法的簡單實例的相關資料,這里提供實例幫助大家應用這樣的加密算法,需要的朋友可以參考下
    2017-09-09
  • SpringBoot中異步調用時的注意事項

    SpringBoot中異步調用時的注意事項

    這篇文章主要介紹了SpringBoot中異步調用時的注意事項,調用的異步方法,不能為同一個類的方法(包括同一個類的內部類),簡單來說,因為Spring在啟動掃描時會為其創(chuàng)建一個代理類,而同類調用時,還是調用本身的代理類的,所以和平常調用是一樣的,需要的朋友可以參考下
    2023-11-11
  • Java開發(fā)之Lombok指南

    Java開發(fā)之Lombok指南

    Lombok是一款Java開發(fā)插件,使得Java開發(fā)者可以通過其定義的一些注解來消除業(yè)務工程中冗長和繁瑣的代碼,它能夠在編譯源代碼期間自動幫我們生成這些方法,并沒有如反射那樣降低程序的性能。下面我們來詳細了解一下吧
    2019-06-06
  • Java JDK與cglib動態(tài)代理有什么區(qū)別

    Java JDK與cglib動態(tài)代理有什么區(qū)別

    這篇文章主要介紹了Java JDK動態(tài)代理和cglib動態(tài)代理的區(qū)別文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧
    2023-03-03
  • Hibernate中使用HQLQuery查詢全部數據和部分數據的方法實例

    Hibernate中使用HQLQuery查詢全部數據和部分數據的方法實例

    今天小編就為大家分享一篇關于Hibernate中使用HQLQuery查詢全部數據和部分數據的方法實例,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • SpringBoot Actuator埋點和監(jiān)控及簡單使用

    SpringBoot Actuator埋點和監(jiān)控及簡單使用

    最近做的項目涉及到埋點監(jiān)控、報表、日志分析的相關知識,于是搗鼓的一番,下面把涉及的知識點及SpringBoot Actuator埋點和監(jiān)控的簡單用法,給大家分享下,感興趣的朋友一起看看吧
    2021-11-11
  • dubbo自定義異常的完整步驟與測試

    dubbo自定義異常的完整步驟與測試

    最近在項目上遇到一個有關dubbo的問題,想著給大家總結下,這篇文章主要給大家介紹了關于dubbo自定義異常的完整步驟與測試的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-06-06
  • 基于java實現(xiàn)DFA算法代碼實例

    基于java實現(xiàn)DFA算法代碼實例

    這篇文章主要介紹了基于java實現(xiàn)DFA算法代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-09-09
  • java寫入文件的幾種方法分享

    java寫入文件的幾種方法分享

    這篇文章主要介紹了java寫入文件的幾種方法,需要的朋友可以參考下
    2014-02-02
  • 關于SpringBoot的異?;貪L和事務的使用詳解

    關于SpringBoot的異?;貪L和事務的使用詳解

    這篇文章主要介紹了關于SpringBoot的異常回滾和事務的使用詳解,Spring中 @Transactional 注解,默認情況下,只對拋出的RuntimeException 異常,才會事務回滾,需要的朋友可以參考下
    2023-05-05

最新評論

玉林市| 龙川县| 通榆县| 湘西| 中牟县| 临湘市| 巴林左旗| 兰考县| 齐河县| 嵩明县| 农安县| 吉隆县| 仁怀市| 微博| 东方市| 什邡市| 普安县| 惠东县| 政和县| 余干县| 皮山县| 汉川市| 霍林郭勒市| 内丘县| 淮北市| 汤原县| 句容市| 库车县| 弋阳县| 当阳市| 凤台县| 临猗县| 都匀市| 萨迦县| 额尔古纳市| 怀仁县| 鹤山市| 丹凤县| 京山县| 洛宁县| 温州市|