Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional objects spring boot - get object fields

I have defined customer entity

@Entity
@Table(name = "customer")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;
    @Column(name = "name")
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

and CrudRepository

public interface CustomerRepo extends CrudRepository<Customer, Long> {
}

if I use CustomerRepo.findById method for finding Customer

@Autowired
CustomerRepo repo;

Optional<Customer> dbCustomer = repo.findById(id);

how can I get name of that customer. I cannot use getter then. so I'm interested is there any solution of using getters of Optional, or I need to use other method for finding Customer by id?

like image 713
Ante Ereš Avatar asked Apr 03 '18 09:04

Ante Ereš


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 we use an Optional object?

Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.

Can Optional get return null?

Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null . It should always point to an Optional instance.


1 Answers

Optional<Customer> is returned, because it is not guaranteed that there will be such a customer with the requested ID in the database. Instead of returning null it simply means that Optional.isPresent() will return false when the ID does not exist.

According to the API Docs (https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#findById-ID-):

Returns:
the entity with the given id or Optional#empty() if none found

You will therefore probably want to simply use the methods on Optional to check whether it contains a Customer (i.e. a Customer with that ID exists), and then get the name like so:

Optional<Customer> dbCustomer = repo.findById(id);
if(dbCustomer.isPresent()) {
    Customer existingCustomer = dbCustomer.get();
    String nameWeWanted = existingCustomer.getName();
    //operate on existingCustomer
} else {
    //there is no Customer in the repo with 'id'
}

Alternatively you can try callback style (shown with Java 8 Lambda):

Optional<Customer> dbCustomer = repo.findById(id);
dbCustomer.ifPresent(existingCustomer -> {
    String nameWeWanted = existingCustomer.getName();
    //operate on existingCustomer
});

It is worth noting that it is possible to check existence of the ID without actually retrieving/loading the entity by using the interface method:

boolean CrudRepository.existsById(ID id)

This saves an entity load, but it still requires a database roundtrip.

like image 77
Thomas Timbul Avatar answered Oct 12 '22 23:10

Thomas Timbul