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?
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.
Optional<String> value = Optional. of(str[ 2 ]); // It returns value of an Optional.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With