gene b.
gene b.

Reputation: 11996

How to work with Spring Data's Optional<Object> Returns

We have a patchwork of Hibernate-gnerated domain objects, e.g.

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

With Spring Data, I can't do

RecallsT recallsT = recallsDAO.findById(recallId);

I'm forced to do

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

but this introduces another issue: now I can't use my Hibernate objects anymore, because this won't work:

eventsT.setRecallsT(recallsT);

Now the error will be that it can't fit an "Optional<...>" object into a plain Object. As I showed in the Hibernate entity, the setter takes a straight plain object because of the traditional way our domain objects were generated.

What to do?

Upvotes: 7

Views: 3680

Answers (2)

rahulnikhare
rahulnikhare

Reputation: 1486

You can also write:

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

Upvotes: 1

ledniov
ledniov

Reputation: 2382

You can write instead

recallsT.ifPresent(eventsT::setRecallsT);

Optional represents possible absence of data, and has methods to work with this wrapper. More info about correct usage of optional is here.

Upvotes: 10

Related Questions