【问题标题】:How can I reach database as json value when i request on my local browser?当我在本地浏览器上请求时,如何将数据库作为 json 值访问?
【发布时间】:2021-06-18 09:43:52
【问题描述】:

注意:这是一个与其他表上的数据库有连接的项目。我刚刚制作了一个新表但我的代码一定有问题,因为我无法得到我想要的。 我有一个City 表,这个表has 3 columns,名为id,名称为city_id。而且我导入了一个csv文件,所以当我查询时,我可以看到一些数据。

我在 Eclipse 上的 Java 中写了 EntityRepositoryControllerService

我该怎么办?例如,当我搜索 localhost:8181/mfc/city/getAllCities 时,它应该给我所有的城市 json

你能告诉我应该添加什么吗?

City.java

package com.mfc.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="city")
public class City{
    
    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    int id;
    
    @Column(name="city_name")
    String cityName;
    
    @Column(name="city_id")
    int cityId;
    
    public City() {
        super();
    }
    
    public City(int id, String cityName, int cityId) {
        super();
        this.id = id;
        this.cityName = cityName;
        this.cityId = cityId;
    }
    
    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;
    }
    
    public int getCityId() {
        return cityId;
    }
    
    public void setCityId(int cityId) {
        this.cityId = cityId;
    }
}

CityController.java

package com.mfc.admin.controller;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.mfc.admin.service.CityService;
import com.mfc.entity.City;

@RestController
@RequestMapping("/city")
public class CityController {
    
    private static final Logger logger = LogManager.getLogger(CityController.class);

    @Autowired
    CityService cityService;
    
    @RequestMapping(value="/getAllCities", method=RequestMethod.GET, headers = "Accept=application/json")
    public List getCities() {
        logger.trace("CityController: getAllCities begins");
        List listOfCities = cityService.getAllCities();
        
        logger.trace("CityController: getAllCities ends");
        return listOfCities;
    }
    
    
    @RequestMapping(value="/getCity/{id}", method=RequestMethod.GET, headers = "Accept=application/json")
    public City getCityById(@PathVariable int id) {
        return cityService.getCity(id);
    }
    
}

CityService.java

package com.mfc.admin.service;    

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mfc.entity.City;
import com.mfc.repository.CityRepository;

@Service("cityService")
public class CityService {
    
    @Autowired
    CityRepository cityDTO;
    
    @Transactional
    public List getAllCities() {
        return cityDTO.getAllCities();
    }
    
    @Transactional
    public City getCity(int id) {
        return cityDTO.getCity(id); // getCity is red here, there is mistake i guess
    }
    
}

CityRepository.java

package com.mfc.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.mfc.entity.City;

public interface CityRepository extends JpaRepository<City, Integer>{

    List getAllCities();
    City getCity();
    
}

【问题讨论】:

    标签: java postgresql jpa


    【解决方案1】:

    CityService 中你像这样调用CityRepository

    return cityDTO.getCity(id); // getCity is red here, there is mistake i guess

    但是CityRepository 中没有定义这样的方法。尝试使用此行return cityDTO.findById(id).get();

    您在CityRepository 中看不到方法findById(Integer id),但它存在,因为CityRepository 扩展了JpaRepository&lt;City, Integer&gt;。查找一些 Spring Data 教程以了解这里的实际情况,长话短说 Spring Data 能够为您生成许多标准方法。

    方法 cityDTO.findById(id) 返回Optional&lt;City&gt;,而不是City。要获取 City 的实例,只需添加 '.get()' 方法,就像在示例中一样。如果数据库中存在城市,它应该对您有用。要正确使用Optional,请查找一些教程。它是可能存在或不存在的对象的包装器,详细说明超出了此答案的范围。

    【讨论】:

    • 我是这个宁静的杂物服务的新手。我无法理解你的意思:/
    • 我已经编辑了我的答案以解释更多细节。
    • 非常感谢您的清晰解释。所以你认为我走对了吗,或者我应该像这样改变我的 CityController:public @ResponseBody List&lt;CityDTO&gt; getCities() { List&lt;CityDTO&gt; cityDTOList = new ArrayList&lt;CityDTO&gt;(); List&lt;City&gt; cityList = cityService.findAll(); for(City city:cityList) { CityDTO cityDTO = new CityDTO(); BeanUtils.copyProperties(city, cityDTO); cityDTO.setSelectable(true); cityDTOList.add(cityDTO); } } logger.trace("CityController: getAllCities ends"); return cityDTOList; }
    • 顺便说一句,即使我在 CityService Sir 中写了这个,它仍然显示“红色”,上面写着 this method is undefined in CityRepository @Transactional public City getCity(int id) { return cityDTO.findById(id); }
    • 我的错,我已经把代码写出来了。我没有意识到方法 findById 返回可选。我会编辑我的答案
    【解决方案2】:

    也许你可以尝试手动设置消息转换器,谷歌 MappingJackson2HttpMessageConverter 你会知道该怎么做。

    【讨论】:

    • 已经搜索了它的含义,但据我所知,我应该在实体、控制器、服务和存储库之间建立连接。但我缺少部分......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2015-03-30
    相关资源
    最近更新 更多