一、使用单元测试
单元测试在每个项目环境中必不可少,springboot中如何使用单元测试
在src/test/java中新建测试类DemoApplicationTest.java
项目结构:
DemoApplicaytionTest.java内容
package springboot_jpa_jsp; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.king.app.App; import com.king.entity.User; import com.king.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = App.class) public class DemoApplicaytionTest { @Autowired private UserService userService; @Test public void testUser() { User u = userService.findOne("1"); System.out.println(u.toString()); } }
此时,直接右键运行Junit测试即可
二、查询方法
1. 使用jpa的命名查询
当使用findBy/readBy/getBy + 某个字段时,比如:
User findById(String id);
也可以多字段查询,如:
List<User> findByCodeAndUsername(String code,String username);
spring jpa的相关命名规则如下:
Keyword | Sample | JPQL snippet |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2. 自定义注解查询
除了继承JpaRepository中的命名方法,有时候不可避免的要自定义查询方法。上面的单元测试中findOne就是自定义的查询方法。
使用@Query注解来查询,注解查询本质上仍然使用的是HQL语法,所以下面的是针对对象查询的。(我在测试时由于粗心大意将User写成user被坑了不少时间)
@Query("select u from User u where u.id = :id")
User findOne(@Param("id")String id);