Spring-boot官方案例分析之data-jpa
Spring-boot官方案例分析之data-jpa
package sample.data.jpa;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Integration test to run the
application.
*
* @author Oliver
Gierke
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleDataJpaApplication.class)
@WebAppConfiguration
@ActiveProfiles("scratch")
// Separate profile for web tests to avoid clashing databases
public class SampleDataJpaApplicationTests {
@Autowired
private WebApplicationContext
context;
private MockMvc mvc;
@Before
public void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void testHome() throws Exception
{
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("Bath"));
}
}
- 首先测试类中选择了要使用的配置文件
@ActiveProfiles(“scratch”)
对应的properties为application-scratch.properties
内容为:
spring.datasource.url: jdbc:hsqldb:mem:scratchdb
定义了数据源的url;
@Autowired
private WebApplicationContext context;
注入应用上下文context;
定义MockMvc,然后@Before注解执行初始化容器
@Before
public void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
然后模拟发送请求测试:
类图关系:
根据这个测试用例来走一遍请求处理过程:
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("Bath"));
get请求处理:到SampleController
@Autowired
private CityService cityService; @RequestMapping("/")
@ResponseBody
@Transactional(readOnly = true)
public String helloWorld() {
return this.cityService.getCity("Bath", "UK").getName();
}
}
注入了CityService组件属性,事务类型为只读。
然后执行服务组件CityService中的getCity()方法;
并且传入参数name=”Bath”,country=”UK”,然后调用getname方法获取name值。
public interface CityService {
Page<City> findCities(CitySearchCriteria criteria, Pageable pageable);
City getCity(String name, String country);
Page<HotelSummary> getHotels(City city, Pageable pageable);
}
该接口中定义了查询方法;
把返回值存在Page对象中
在实现类中,标记为组件并设置id=cityService;这样程序执行会找到impl类;
@Component("cityService")
@Transactional
class CityServiceImpl implements CityService {
private final CityRepository cityRepository;
private final HotelRepository hotelRepository;
@Autowired
public CityServiceImpl(CityRepository cityRepository, HotelRepository hotelRepository) {
this.cityRepository = cityRepository;
this.hotelRepository = hotelRepository;
}
@Override
public Page<City> findCities(CitySearchCriteria criteria, Pageable pageable) {
Assert.notNull(criteria, "Criteria must not be null");
String name = criteria.getName();
if (!StringUtils.hasLength(name)) {
return this.cityRepository.findAll(null);
}
String country = "";
int splitPos = name.lastIndexOf(",");
if (splitPos >= 0) {
country = name.substring(splitPos + 1);
name = name.substring(0, splitPos);
}
return this.cityRepository
.findByNameContainingAndCountryContainingAllIgnoringCase(name.trim(),
country.trim(), pageable);
}
@Override
public City getCity(String name, String country) {
Assert.notNull(name, "Name must not be null");
Assert.notNull(country, "Country must not be null");
return this.cityRepository.findByNameAndCountryAllIgnoringCase(name, country);
}
@Override
public Page<HotelSummary> getHotels(City city, Pageable pageable) {
Assert.notNull(city, "City must not be null");
return this.hotelRepository.findByCity(city, pageable);
}
}
由于执行的是事务操作所以要加上@Transactional
通过构造函数注入其他组件;
@Override
public City getCity(String name, String country) {
Assert.notNull(name, "Name must not be null");
Assert.notNull(country, "Country must not be null");
return this.cityRepository.findByNameAndCountryAllIgnoringCase(name, country);
}
在该方法中进行断言判断是否为空,然后执行Dao查询;在jpa中会通过不同的关键字在接口中定义方法名来映射为sql查询语句,上面方法相当于select * from city c where name=”bath” 返回的是一个city对象,前提是name值唯一确定。
Spring-boot官方案例分析之data-jpa的更多相关文章
- 精尽Spring Boot源码分析 - Jar 包的启动实现
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
- 精尽Spring Boot源码分析 - 剖析 @SpringBootApplication 注解
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
- 精尽Spring Boot源码分析 - Condition 接口的扩展
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
- Spring Boot 入门详细分析
推荐阅读: 我们为什么要学习 Spring Boot 我们搭建 Spring Boot 项目,可以使用 Spring 为我们提供的初始化网站,那个可能不太方便,今天呢,我们就来说说如何使用 IDEA ...
- Spring-boot官方案例分析之log4j
Spring-boot官方案例分析之log4j 运行单元测试分析: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfigur ...
- Spring Boot源码分析-配置文件加载原理
在Spring Boot源码分析-启动过程中我们进行了启动源码的分析,大致了解了整个Spring Boot的启动过程,具体细节这里不再赘述,感兴趣的同学可以自行阅读.今天让我们继续阅读源码,了解配置文 ...
- Spring Boot源码分析-启动过程
Spring Boot作为目前最流行的Java开发框架,秉承"约定优于配置"原则,大大简化了Spring MVC繁琐的XML文件配置,基本实现零配置启动项目. 本文基于Spring ...
- 精尽Spring Boot源码分析 - 序言
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
- 精尽Spring Boot源码分析 - 文章导读
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
随机推荐
- Checkbox与foreach循环
呈现形态&控件语法 <span style=”display:inline-block;”> <input id=”checkBox2” type=”checkBox” na ...
- 使用waitfor 语句
aitfor语句用于延迟后面语句的执行,可以指定延迟时间长度是具体的时间.参考下面的语句: waitfor delay ’00:01:15’ print N’到时间了’ --也可以不加N 字符串 ...
- OpenLayers 3 给features 添加手势
map.on('pointermove',function(e){ var pixel = map.getEventPixel(e.originalEvent); var hit = map.hasF ...
- iDempiere 使用指南 windows下eclipse开发环境配置及打包下载
Created by 蓝色布鲁斯,QQ32876341,blog http://www.cnblogs.com/zzyan/ iDempiere官方中文wiki主页 http://wiki.idemp ...
- 【阿里云产品公测】简单粗暴30S完成PTS测试配置附tornado服务器测试结果
作者:阿里云用户morenocjm [阿里云产品公测]简单粗暴 30S完成PTS测试配置(附tornado服务器测试结果) -------------------------------------- ...
- 彻底解决INSTALL_FAILED_UPDATE_INCOMPATIBLE的安装错误
利用adb shell进入系统,进入/data/app或者/data/data,删除跟你安装的apk同样的包名: 按Ctrl+C退出系统,利用adb pull /data/system/package ...
- CodeMirror教程,CodeMirrorAPI中文信息
<html> <head> <link rel="stylesheet" href="codemirror.css"> ...
- Azure 9 月新发布
亲爱的小伙伴们, 我们很高兴向您宣布以下新功能与相关调整,欢迎关注与使用. 1. SQL 数据库弹性池 2. 存储指标更新 3. SQL 数据库 P15 4. Azure 高级存储 5. Wosig ...
- EM自动任务导致数据库缓慢
这两天客户抱怨数据库慢,查看性能什么的没发现什么异常.查看job发现一个内容为EMD_MAINTENANCE.EXECUTE_EM_DBMS_JOB_PROCS执行特别频繁.使用 EXEC DBMS_ ...
- 【转】ssh timed out 超时解决方案
转自:http://www.cnblogs.com/niutouzdq/p/4091268.html 在使用阿里云ECS服务器的时候,winsftp经常被服务器断开,想必是过一会没有操作,防火墙喜欢对 ...