Spring框架對(duì)SQL數(shù)據(jù)庫提供了廣泛的支持庐氮。本文介紹如何在Spring Boot中使用Spring Data Jpa來訪問MySQL數(shù)據(jù)庫薪夕。
準(zhǔn)備工作
我們從國家統(tǒng)計(jì)局網(wǎng)站找來了《最新縣及縣以上行政區(qū)劃代碼》(截止2015年9月30日)桃纯,并將其錄入數(shù)據(jù)庫酷誓。SQL文件見本文例子程序中的region.sql文件。
開始編碼
1态坦、添加依賴
在上文的例子的基礎(chǔ)上盐数,我們?cè)诠こ痰?code>pom.xml文件中添加spring-boot-starter-data-jpa
和mysql-connector-java
的依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
同時(shí)添加常用的第三方庫apache-commons-lang3
和google-guava
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
2伞梯、在application.properties
文件中添加數(shù)據(jù)庫連接信息
#MySQL Configuration
spring.datasource.url=jdbc:mysql://localhost/quickstart
spring.datasource.username=root
spring.datasource.password=fuyongde
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3玫氢、在src\main\java\com\jason\entity
目錄下編寫Region.java
實(shí)體類,代碼冗余谜诫,詳見本文例子程序漾峡。
4、在src\main\java\com\jason\repository
目錄下編寫Dao層的接口喻旷。由于Spring Data JPA實(shí)現(xiàn)了大量的方法生逸,我們按如下方式寫即可。
package com.jason.repository;
import com.jason.entity.Region;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface RegionDao extends PagingAndSortingRepository<Region, Integer>, JpaSpecificationExecutor<Region> {
}
5且预、在src\main\java\com\jason\service
目錄項(xiàng)編寫Service層的接口及其實(shí)現(xiàn)類槽袄。此處只貼實(shí)現(xiàn)類相關(guān)的代碼,詳見本文例子程序辣之。
package com.jason.service.impl;
import com.jason.entity.Region;
import com.jason.repository.RegionDao;
import com.jason.service.RegionService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class RegionServiceImpl implements RegionService {
@Resource
private RegionDao regionDao;
@Override
public Region getById(Integer id) {
return regionDao.findOne(id);
}
}
6掰伸、在src\main\java\com\jason\rest
目錄編寫Controller層代碼。此處我們遵循Restful風(fēng)格的編碼怀估,Restful風(fēng)格的編碼詳見Oracle網(wǎng)站以及Rest API Tutorial狮鸭。
package com.jason.rest;
import com.jason.entity.Region;
import com.jason.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(value = "/api/regions")
public class RegionRestController {
@Autowired
private RegionService regionService;
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Region getRegionById(@PathVariable("id") Integer id) {
Region result = regionService.getById(id);
return result;
}
}
7、運(yùn)行該程序多搀,訪問http://localhost:8080/black/api/regions/110000
歧蕉,即可看到北京的地區(qū)信息。
{
"id": 110000,
"parentId": 0,
"name": "北京市",
"level": 1
}
編寫單元測試
? 不同于之前文章所寫的測試方法康铭,本文的單元測試需要配置WebApplicationContext
惯退,測試類如下。
package com.jason.rest;
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.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
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.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class RegionRestControllerTest {
private MockMvc mvc;
@Autowired
private WebApplicationContext context;
@Before
public void before() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void testGetRegionById() throws Exception {
this.mvc.perform(get("/api/regions/110000").accept(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.name").value("北京市"));
}
}
本文示例程序請(qǐng)點(diǎn)此獲取从藤。
詳細(xì)資料請(qǐng)參考Spring Boot官網(wǎng)催跪。