本文介绍了JPA Repository 'getOne(id)' 方法的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 Report 类型的对象提供以下 Spring boot 服务 -

I have the following Spring boot service for an object of type Report -

    @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 不存在,则会生成以下错误...

The problem arises while retrieving a single Report. If a report ID is send which doesn't exist, the following error is generated...

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...
}

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

Below is the code for my Report Model class -

@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,以便我可以实际检查数据库中是否不存在特定报告.如果没有,我还能如何实现上述内容?

I want to know if reportRepository.getOne(Long id) returns null so that I can actually check if a particular report doesn't exist in the database. If not, how else can I implement the above?

推荐答案

JpaRepository.getOne with throw EntityNotFoundException 如果找不到给定 id 的记录.

The JpaRepository.getOne with throw EntityNotFoundException if it couldn't find a record with the given id.

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

You can use CrudRepository.findById (JpaRepository is a subclass of CrudRepository) which will return an Optional<Report> which can be empty if there are no record for the given id. You can use Optional.isPresent() to check whether it a Report is available or not and take actions accordingly.

这篇关于JPA Repository 'getOne(id)' 方法的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 19:02