一、使用单元测试
单元测试在每个项目环境中必不可少,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 |
---|
And
|
findByLastnameAndFirstname
|
… where x.lastname = ?1 and x.firstname = ?2
|
Or
|
findByLastnameOrFirstname
|
… where x.lastname = ?1 or x.firstname = ?2
|
Is,Equals
|
findByFirstname ,findByFirstnameIs ,findByFirstnameEquals
|
… where x.firstname = ?1
|
Between
|
findByStartDateBetween
|
… where x.startDate between ?1 and ?2
|
LessThan
|
findByAgeLessThan
|
… where x.age < ?1
|
LessThanEqual
|
findByAgeLessThanEqual
|
… where x.age <= ?1
|
GreaterThan
|
findByAgeGreaterThan
|
… where x.age > ?1
|
GreaterThanEqual
|
findByAgeGreaterThanEqual
|
… where x.age >= ?1
|
After
|
findByStartDateAfter
|
… where x.startDate > ?1
|
Before
|
findByStartDateBefore
|
… where x.startDate < ?1
|
IsNull
|
findByAgeIsNull
|
… where x.age is null
|
IsNotNull,NotNull
|
findByAge(Is)NotNull
|
… where x.age not null
|
Like
|
findByFirstnameLike
|
… where x.firstname like ?1
|
NotLike
|
findByFirstnameNotLike
|
… where x.firstname not like ?1
|
StartingWith
|
findByFirstnameStartingWith
|
… where x.firstname like ?1 (parameter bound with appended % )
|
EndingWith
|
findByFirstnameEndingWith
|
… where x.firstname like ?1 (parameter bound with prepended % )
|
Containing
|
findByFirstnameContaining
|
… where x.firstname like ?1 (parameter bound wrapped in % )
|
OrderBy
|
findByAgeOrderByLastnameDesc
|
… where x.age = ?1 order by x.lastname desc
|
Not
|
findByLastnameNot
|
… where x.lastname <> ?1
|
In
|
findByAgeIn(Collection<Age> ages)
|
… where x.age in ?1
|
NotIn
|
findByAgeNotIn(Collection<Age> age)
|
… where x.age not in ?1
|
True
|
findByActiveTrue()
|
… where x.active = true
|
False
|
findByActiveFalse()
|
… where x.active = false
|
IgnoreCase
|
findByFirstnameIgnoreCase
|
… where UPPER(x.firstame) = UPPER(?1)
|
2. 自定义注解查询
除了继承JpaRepository中的命名方法,有时候不可避免的要自定义查询方法。上面的单元测试中findOne就是自定义的查询方法。
使用@Query注解来查询,注解查询本质上仍然使用的是HQL语法,所以下面的是针对对象查询的。(我在测试时由于粗心大意将User写成user被坑了不少时间)
@Query("select u from User u where u.id = :id")
User findOne(@Param("id")String id);