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"));
   }
}

  1. 首先测试类中选择了要使用的配置文件

@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的更多相关文章

  1. 精尽Spring Boot源码分析 - Jar 包的启动实现

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  2. 精尽Spring Boot源码分析 - 剖析 @SpringBootApplication 注解

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  3. 精尽Spring Boot源码分析 - Condition 接口的扩展

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  4. Spring Boot 入门详细分析

    推荐阅读: 我们为什么要学习 Spring Boot 我们搭建 Spring Boot 项目,可以使用 Spring 为我们提供的初始化网站,那个可能不太方便,今天呢,我们就来说说如何使用 IDEA ...

  5. Spring-boot官方案例分析之log4j

    Spring-boot官方案例分析之log4j 运行单元测试分析: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfigur ...

  6. Spring Boot源码分析-配置文件加载原理

    在Spring Boot源码分析-启动过程中我们进行了启动源码的分析,大致了解了整个Spring Boot的启动过程,具体细节这里不再赘述,感兴趣的同学可以自行阅读.今天让我们继续阅读源码,了解配置文 ...

  7. Spring Boot源码分析-启动过程

    Spring Boot作为目前最流行的Java开发框架,秉承"约定优于配置"原则,大大简化了Spring MVC繁琐的XML文件配置,基本实现零配置启动项目. 本文基于Spring ...

  8. 精尽Spring Boot源码分析 - 序言

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  9. 精尽Spring Boot源码分析 - 文章导读

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

随机推荐

  1. jquery点滴总结

    1.empty().remove().detach() empty():只移除了 指定元素中的所有子节点,而留下 了<p></p>,仍保留其在dom中所占的位置. remove ...

  2. javascript数组与字符串之间转换

    一.数组转字符串(将数组元素用某个字符连接成字符串) var a, b;a = new Array(0,1,2,3,4);b = a.join("-"); 二.字符串转数组(将字符 ...

  3. Mysql数据库死锁分析相关概念

    参考博客: mysql死锁问题分析(https://www.cnblogs.com/LBSer/p/5183300.html) mysql insert锁机制(http://yeshaoting.cn ...

  4. 封装微信jssdk自定义分享代码

    var protocol = window.location.protocol; //获取协议 var host = window.location.host; //获取域名 var posuDoma ...

  5. matlab练习程序(圆柱投影)

    圆柱投影就是将一张二维的图像投影到三维的圆柱体上,不过在显示图像的时候依然是以二维的形式给出. 投影最重要的步骤就是计算投影变换公式,和图像旋转类似,只要得到变换公式,再依照公式进行代码编写就很容易了 ...

  6. Filter学习总结,顺便提及点servlet3.0异步filter和异步监听

      Filter介绍:     Filter在项目中经常可以用到,通常配置在web.xml中.是服务器端的一个组件,对于用户的请求和响应数据进行过滤操作,控制是否让用户访问到对应的web资源.常用于编 ...

  7. C# linq to sql

    参考文章地址:http://www.cnblogs.com/yubaolee/p/BestLinqQuery.html   以下是我自己的总结: 表结构: 本文全部代码基于:UserInfo与Clas ...

  8. python闭包&装饰器&偏函数

    什么是闭包? 首先还得从基本概念说起,什么是闭包呢?来看下维基上的解释: 在计算机科学中,闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数.这个被引用的 ...

  9. solidity语言4

    引用类型(Reference Types) memory 不支持持久保存 storage 保留为变量 复杂类型如arrays和structs,有附加信息,'data location',提示存储在'm ...

  10. Markdown 使用方法总结

    标题: [#]  表示一级标题 [##] 表示二级标题 [###]表示三级标题 引用块:在引用文本前插入 Tab,具体几个 Tab 根据文本所处的位置不同而不同 列表:[ - ]即一个空格加上一个中划 ...