spingboot集成jpa(二)
一、使用单元测试
单元测试在每个项目环境中必不可少,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);
最新文章
- [(ngModel)]的实现原理
- ES5基础01:正则表达式
- 查看Linux硬件配置信息
- Android项目——传感器的使用
- hdu 1044 Collect More Jewels(bfs+状态压缩)
- USB挂起与唤醒.
- Linux学习1——首次登录
- Swift - 协议(protocol)
- bigdata之hadoop and spark
- 如何解决找不到方法HttpServletRequest.getServletContext() ---- NoSuchMethodError
- flex stage.width 与stage.stageWidth的区别
- python note 08 文件操作
- django xadmin拓展User模型
- MEF 插件式开发之 WPF 初体验
- VUE路由转场特效,WebAPP的前进与后退
- HiKey软硬件开发环境及其调试
- 数据分析--降维--LDA和PCA
- 微博推荐算法学习(Weibo Recommend Algolrithm)
- 如何修改opencart的模版适合为mycncart系统使用
- java项目学习