一、引入jpa的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
二、创建数据库表相对应的实体类,其中驼峰和下划线会做自动映射
package cn.edu.tju.domain;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class City {
@Id
private int id;
private String cityName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
}
三、创建Repository接口,并按照jpa的规则在其中定义方法:
package cn.edu.tju.repository;
import cn.edu.tju.domain.City;
import org.springframework.data.repository.Repository;
import java.util.List;
@org.springframework.stereotype.Repository
public interface CityRepository extends Repository<City,Integer> {
List<City> findAll();
List<City> findByCityName(String name);
}
四、在控制器中注入Repository类
package cn.edu.tju.controller;
import cn.edu.tju.domain.City;
import cn.edu.tju.repository.CityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class CityController {
@Autowired
private CityRepository cityRepository;
@RequestMapping("/getCityList")
public List<City> getCityList(){
List<City> cityList = cityRepository.findAll();
return cityList;
}
@RequestMapping("/getCity/{cityName}")
public List<City> getCity(@PathVariable("cityName")String cityName){
List<City> cityList = cityRepository.findByCityName(cityName);
return cityList;
}
}
五、示意运行结果
数据库数据如下: