Optional objects spring boot - get object fields
Asked Answered
Q

2

6

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?

Quint answered 3/4, 2018 at 9:50 Comment(4)
Add a method in the repo for finding customer by id, and then you can use like this Customer dbCustomer = repo.findById(id);Lockyer
I tried and getting "Incompatible types. Required: com.fitnet.phonqpon.models.Customer Found: java.util.Optional <com.fitnet.phonqpon.models.Customer>"........ but if I add Customer findById (Long id); method inside of CustomerRepo interface I am getting "'findById(Long)' in 'com.fitnet.phonqpon.repositories.CustomerRepo' clashes with 'findById(ID)' in 'org.springframework.data.repository.CrudRepository'; attempting to use incompatible return type"Apologist
You can change the field name of your primary key to customerId or something and add a method in repo like findByCustomerId(Long id)Lockyer
id is field name of my primary keyApologist
G
23

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.

Gearldinegearshift answered 3/4, 2018 at 10:24 Comment(1)
Thank you Thomas. That helped me.Apologist
M
-1

Try to use another method for finding Customer:

@Autowired
CustomerRepo repo;

Customer dbCustomer = repo.findOne(id);
Meanly answered 3/4, 2018 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.