springboot实现省市区三级联查
在Spring Boot中实现省市区三级联查,通常需要建立数据库表格来存储省、市、区的数据,并提供相应的API接口。以下是一个简单的示例:
- 创建数据库表格:
CREATE TABLE `region` (
`id` bigint NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`parent_id` bigint DEFAULT NULL,
PRIMARY KEY (`id`)
);
- 实体类(Region.java):
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Region {
@Id
private Long id;
private String name;
private Long parentId;
// 省略getter和setter
}
- Repository接口(RegionRepository.java):
import org.springframework.data.jpa.repository.JpaRepository;
public interface RegionRepository extends JpaRepository<Region, Long> {
List<Region> findByParentId(Long parentId);
}
- 服务类(RegionService.java):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class RegionService {
@Autowired
private RegionRepository regionRepository;
public List<Region> getProvinceList() {
return regionRepository.findByParentId(null);
}
public List<Region> getCityList(Long provinceId) {
return regionRepository.findByParentId(provinceId);
}
public List<Region> getDistrictList(Long cityId) {
return regionRepository.findByParentId(cityId);
}
}
- 控制器类(RegionController.java):
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class RegionController {
@Autowired
private RegionService regionService;
@GetMapping("/region/province")
public List<Region> getProvinceList() {
return regionService.getProvinceList();
}
@GetMapping("/region/city")
public List<Region> getCityList(@RequestParam Long provinceId) {
return regionService.getCityList(provinceId);
}
@GetMapping("/region/district")
public List<Region> getDistrictList(@RequestParam Long cityId) {
retur
评论已关闭