Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 278
gene b. Avatar asked Dec 14 '17 21:12

gene b.


People also ask

How do I retrieve an object from optional?

Once you have created an Optional object, you can use the isPresent() method to check if it contains a non-null value. If it does, you can use the get() method to retrieve the value. Developers can also use the getOrElse() method, which will return the value if it is present, or a default value if it is not.

How can I return optional value in Java?

Optional<String> value = Optional. of(str[ 2 ]); // It returns value of an Optional.

What is difference between JpaRepository and CrudRepository?

CrudRepository: provides CRUD functions. PagingAndSortingRepository: provides methods to do pagination and sort records. JpaRepository: provides JPA related methods such as flushing the persistence context and delete records in a batch.


1 Answers

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.

like image 179
ledniov Avatar answered Nov 14 '22 02:11

ledniov