【问题标题】:Return type of JPA Repository 'getOne(id)' MethodJPA Repository 'getOne(id)' 方法的返回类型
【发布时间】:2018-08-09 04:37:34
【问题描述】:

对于Report 类型的对象,我有以下Spring boot 服务 -

    @Service
    public class ReportService {

        @Autowired
        private ReportRepository reportRepository;

        @Autowired
        private UserRepository userRepository;

        /*get all reports */
        public List<Report> getAllReports(){
            return reportRepository.findAll();
        }

        /*get a single report */
        public Report getReport(Long id){
            return reportRepository.getOne(id);
        }
        //other similar methods....
    }

在检索单个报告时出现问题。如果发送的报告 ID 不存在,则会生成以下错误...

DefaultHandlerExceptionResolver : Failed to write HTTP message: 
org.springframework.http.converter.HttpMessageNotWritableException: Could not 
write JSON: Unable to find com.interact.restapis.model.Report with id 16; 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: 
Unable to find com.interact.restapis.model.Report with id 16 (through 
reference chain: 
com.interact.restapis.model.Report_$$_jvst83c_1["fromUserId"])

下面是我的报告代码Controller

@RestController
public class ReportController {

    @Autowired
    private ReportService reportService;

    //Get all reports
    @GetMapping("/interactions")
    public List<Report> getAllReports() {
        return reportService.getAllReports();
    }

    //Get single report
    @GetMapping("/interactions/{id}")
    public ResponseEntity<Report> getReport(@PathVariable Long id) {
        if(reportService.getReport(id) == null)
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        return new ResponseEntity<>(reportService.getReport(id), HttpStatus.OK);
    }

    @PostMapping("/interactions")
    public ResponseEntity<Report> addReport(@RequestBody Report report) {
        Report report1 = reportService.addReport(report);
        if(report1 == null)
            return new ResponseEntity<>(report, HttpStatus.NOT_FOUND);
        return new ResponseEntity<>(report1, HttpStatus.OK);
    }
    //Other request methods...
}

下面是我的报告模型类的代码 -

@Entity
@Table (name = "report")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Report {

    @Id
    @Column (name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "from_user_id")
    private Long fromUserId;

    @Column(name = "to_user_id")
    private Long toUserId;

    @Column(name = "to_user_email")
    private String toUserEmail;

    @Column(name = "from_user_email")
    private String fromUserEmail;

    @Temporal(TemporalType.DATE)
    @JsonFormat(pattern = "dd-MM-yyyy hh:mm:ss")
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    private String observation;

    @Column(nullable = false)
    private String context;

    private String recommendation;

    @Column(nullable = false)
    private String eventName;

    @Temporal(TemporalType.DATE)
    @JsonFormat(pattern = "dd-MM-yyyy hh:mm:ss")
    @Column(nullable = false)
    private Date eventDate;

    private boolean isAnonymous;

    @Temporal(TemporalType.DATE)
    @JsonFormat(pattern = "dd-MM-yyyy hh:mm:ss")
    private Date acknowledgementDate;

    @OneToMany(cascade = CascadeType.ALL, targetEntity = Action.class)
    @JoinColumn(name = "report_id")
    private List<Action> actionList;

    @Value("${some.key:0}")
    private int rating; //Range 0 to 4

    private int type;

    /*
    Getter and setter methods...
     */
}

我想知道reportRepository.getOne(Long id) 是否返回null,以便我可以实际检查数据库中是否不存在特定报告。如果没有,我还能如何实现上述内容?

【问题讨论】:

  • 您使用的是哪个版本的spring-data-jpa
  • @MehrajMalik spring-boot-starter-jpa 2.0.3.RELEASE

标签: spring spring-boot spring-data-jpa spring-repositories


【解决方案1】:

JpaRepository.getOneEntityNotFoundException 如果找不到具有给定 id 的记录。

您可以使用CrudRepository.findByIdJpaRepositoryCrudRepository 的子类),它将返回一个Optional&lt;Report&gt;,如果给定的id 没有记录,它可以为空。您可以使用Optional.isPresent() 来检查Report 是否可用并采取相应措施。

【讨论】:

    【解决方案2】:

    在您的ReportRepository 中创建一个方法。 它将通过匹配的 id 返回报告,否则返回 null。

    public Optional<Report>  findById(Long id);
    

    注意:findById(Long id);应与您的 Report 实体中的属性名称匹配。

    我假设您的报告实体如下:

    public class Entity{
    private Long id;
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多