jpa@query 可以写insert 吗

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jpa@query 可以写insert 吗相关的知识,希望对你有一定的参考价值。

可以的,举例如下:
@Modifying
@Query(value = "insert into t_sys_org_user(org_id,user_id) values(?1,?2)",nativeQuery = true)
int addUserToOrg(Long orgId,Long userId);
参考技术A JPA注解就是利用注解来实现JPA相关的配置工作。 在没有使用注解直接,大量的配置通过XML文件来完成,导致维护起来非常困难。 使用注解时,所有的实体相关的配置,都是放到实体类里面,维护的时候打开实体类就能够直接修改

对 Spring Data JPA @Query 进行单元测试是不可能的,真的吗?

【中文标题】对 Spring Data JPA @Query 进行单元测试是不可能的,真的吗?【英文标题】:It's impossible to unit-test a Spring Data JPA @Query, really? 【发布时间】:2019-05-28 13:26:20 【问题描述】:

首先,目标。什么是单元测试?单元测试是测试最小功能的测试,与测试更多的集成测试相反,例如:

以任何方式或任何形式生成生产 ApplicationContext 的测试都不是单元测试; 接触甚至意识到应用程序(标有@SpringBootApplication)类的测试不是单元测试; 从src/main/resources 加载内容的测试不是单元测试 从 Spring Cloud Config 服务器加载外部配置的测试绝对不是单元测试; 存储库的单元测试不得启动(甚至了解)Web、mvc 或安全问题。

那么,如何为 Spring Data JPA 存储库编写单元测试? (或者如此流行和喜爱的框架不支持这种东西的纯单元测试?)

我的项目:Spring Cloud(Cloud Config服务、Security OAuth2服务、eureka、zuul、认证、授权等)

让我们尝试测试最简单的存储库:

public interface StudentRepository extends CrudRepository<Student, Integer> 
    Optional<Student> findByStudentCode(Integer studentCode);
    Optional<Student> findTopByOrderByStudentCodeDesc();

    @Query(value = "SELECT COUNT(*) = 0 FROM t_student WHERE regexp_replace(LOWER(student_name), '\\s', '', 'g') = regexp_replace(LOWER(:suspect), '\\s', '', 'g')", nativeQuery = true)
    boolean isStudentNameSpeciallyUnique(@Param("suspect") String studentName);

学生实体将具有:id、代码(自然 ID)、姓名、年龄。没什么特别的。 这是测试。我们需要一个 SUT(我们的存储库)和实体管理器来预填充 SUT。所以:

@RunWith(SpringRunner.class)
@DataJpaTest // <-- loads full-blown production app context and fails!
public class StudentRepositoryTest 

    @Autowired
    TestEntityManager manager;

    @Autowired
    StudentRepository repository;

    @Test
    public void findByStudentCode_whenNoSuch_shouldReturnEmptyOptional() 
        final int invalidStudentCode = 321;
        Optional<Student> student = repository.findByStudentCode(invalidStudentCode);
        assertFalse(student.isPresent());
    

尝试运行它会产生这样的结果:

...
2019-01-01 18:32:10.750  INFO 15868 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2d72f75e: startup date [Tue Jan 01 18:32:10 EET 2019]; root of context hierarchy
2019-01-01 18:32:11.294  INFO 15868 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2019-01-01 18:32:11.421  INFO 15868 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$9ed1a748] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.6.RELEASE)

2019-01-01 18:32:30.694  INFO 15868 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8888\
...

@DataJpaTest 向上搜索包层次结构并加载生产应用程序:

package org.givespring.atry.university.studentservice;
@EnableResourceServer
@EnableJpaAuditing
@SpringBootApplication(scanBasePackages = "org.givespring.atry.university") // to discover MicroserviceProperties and custom usercontext stuff
public class StudentServiceApp 
    public static void main(String[] args) 
        SpringApplication.run(StudentServiceApp.class, args);
    

结果报错:

2019-01-01 18:32:32.789 ERROR 15868 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Unable to retrieve @EnableAutoConfiguration base packages
    at org.springframework.boot.autoconfigure.AutoConfigurationPackages.get(AutoConfigurationPackages.java:76) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:79) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport$1.getBasePackages(AbstractRepositoryConfigurationSourceSupport.java:73) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.data.repository.config.RepositoryConfigurationSourceSupport.lambda$getCandidates$2(RepositoryConfigurationSourceSupport.java:77) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
    at org.springframework.data.util.LazyStreamable.stream(LazyStreamable.java:50) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
    at org.springframework.data.util.LazyStreamable.iterator(LazyStreamable.java:41) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
    at org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport.getRepositoryConfigurations(RepositoryConfigurationExtensionSupport.java:87) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
    at org.springframework.data.repository.config.RepositoryConfigurationDelegate.registerRepositoriesIn(RepositoryConfigurationDelegate.java:126) ~[spring-data-commons-2.0.11.RELEASE.jar:2.0.11.RELEASE]
    at org.springframework.boot.autoconfigure.data.AbstractRepositoryConfigurationSourceSupport.registerBeanDefinitions(AbstractRepositoryConfigurationSourceSupport.java:60) ~[spring-boot-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.lambda$loadBeanDefinitionsFromRegistrars$1(ConfigurationClassBeanDefinitionReader.java:358) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:1.8.0_121]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsFromRegistrars(ConfigurationClassBeanDefinitionReader.java:357) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:146) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:118) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:328) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:271) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:91) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:692) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:530) ~[spring-context-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) ~[spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) ~[spring-boot-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:127) [spring-boot-test-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:44) [spring-boot-test-autoconfigure-2.0.6.RELEASE.jar:2.0.6.RELEASE]
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190) [spring-test-5.0.10.RELEASE.jar:5.0.10.RELEASE]
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137) [junit-4.12.jar:4.12]
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) [junit-rt.jar:na]
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70) [junit-rt.jar:na]

2019-01-01 18:32:32.792  INFO 15868 --- [           main] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6a2eea2a: startup date [Tue Jan 01 18:32:32 EET 2019]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@2d72f75e

【问题讨论】:

【参考方案1】:

简而言之,单元测试是一个小单元的快速测试。什么是单元取决于开发人员或架构指南。它可以是任何小的可测试代码,例如方法

另外,如果您考虑一下,您不会为您的存储库编写任何代码。您依赖于 Spring Platform。如果您发现一些错误,请随时提出ticket

因此不需要为 Spring Data JPA 存储库方法编写任何单元测试。

如果您需要为 Spring Data JPA 存储库编写单元测试,我想您关心的问题与方法有关:save、delete、findOne、findAll 等。在这种情况下,如您所见,这不是 small,因此需要进行集成测试

此存储库包含一个使用 spring jpa 存储库方法进行集成测试的示例:

https://github.com/jrichardsz/spring-boot-templates/blob/master/003-hql-database-with-integration-test/src/test/java/test/CustomerRepositoryIntegrationTest.java

参考资料:

https://***.com/a/23442457/3957754 https://www.quora.com/What-is-the-real-efficiency-of-unit-testing

【讨论】:

以上是关于jpa@query 可以写insert 吗的主要内容,如果未能解决你的问题,请参考以下文章

对 Spring Data JPA @Query 进行单元测试是不可能的,真的吗?

Spring JPA Query注解——输入一个sql文件

春季数据 jpa @query 和可分页

Spring Boot 审计@Query

在mybatis中insert语句必须插入表中的全部字段吗??

Spring Boot中的JPA @query中没有传递参数[重复]