如何使用Spring Data的Optional <object>返回

时间:2017-12-14 21:03:50

标签: hibernate java-8 spring-data

我们有一个Hibernate-gnerated域对象的拼凑而成,例如

@Entity
@Table(name = "events_t", schema = "public")
public class EventsT implements java.io.Serializable {    
    private int id;
    private RecallsT recallsT; // another table
}

使用Spring Data,我无法做到

RecallsT recallsT = recallsDAO.findById(recallId);

我被迫做了

Optional<RecallsT> recallsT = recallsDAO.findById(recallId);

但这引入了另一个问题:现在我不能再使用我的Hibernate对象,因为这不会起作用:

eventsT.setRecallsT(recallsT);

现在错误将是它不适合&#34;可选&lt; ...&gt;&#34;将对象转换为普通对象。正如我在Hibernate实体中所展示的那样,setter采用直接的普通对象,因为我们生成了域对象的传统方式。

怎么办?

2 个答案:

答案 0 :(得分:8)

您可以改为编写

<img class="myImg" src="https://cdn.theatlantic.com/assets/media/img/mt/2017/06/GettyImages_675371680/lead_960.jpg?1498239007" alt="Trolltunga, Norway" width="300" height="200">

<img class="myImg" src="https://cdn.theatlantic.com/assets/media/img/mt/2017/06/GettyImages_675371680/lead_960.jpg?1498239007" alt="Trolltunga, Norway" width="300" height="200">

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
  <div id="caption"></div>
</div>
<script>
	// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementsByClassName('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
for(var i = 0; i < img.length;i--){
  img[i].onclick = function() {
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
  }
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}
</script>

可选表示可能缺少数据,并且具有使用此包装器的方法。 有关正确使用可选is here.

的更多信息

答案 1 :(得分:1)

你也可以写:

  private Todo findTodoEntryById(Long id) {
        Optional<Todo> todoResult = repository.findOne(id);
        return todoResult.orElseThrow(() -> new TodoNotFoundException(id));
}