Search code examples
javaspringcouchbasespring-data-couchbase

Can't map the JSON object from Couchbase to DTO entity using Spring Data Couchbase


I have created some Data Model Objects to insert and read from Couchbase. It has simple types and 2 fields are other DTO objects.

@Data
@AllArgsConstructor
@Document
public class Customer {

    @Id
    private int id;

    private String fullName;

    private String phoneNumber;

    private String address;

    private Date registrationDate;

    private boolean isBusiness;

    private String status;

    private Tariff currentTariff;

    private BillingAccount billingAccount;
}

So, I made and endpoint with logic for creating 10 000 of random Customer Objects, then it does repository.saveAll(customers);

I can see this data added in Couchbase UI

But then I want to get all this Customer Objects from Couchbase. Here's my code

    @GetMapping("/findAllCustomers")
    public Iterable<Customer> getAll() {
        return repository.findAll();
    }

Very simple, no custom conversion, no other complicated stuff. The type I'm expecting is exactly the type that I was generating and saving this data with.

I get the following error :

Failed to instantiate com.bachelor.boostr.model.Customer using constructor public com.bachelor.boostr.model.Customer

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer\r\n\tat com.bachelor.boostr.model.Customer_Instantiator_z47nsm.newInstance(Unknown Source)\r\n\tat org.springframework.data.convert.ClassGeneratingEntityInstantiator$EntityInstantiatorAdapter.createInstance(ClassGeneratingEntityInstantiator.java:226)\r\n\t...

Please help


Solution

  • I removed @AllArgsConstructor Lombok Annotation, and created constructor without the Id field

    @Data
    @Document
    public class Customer {
    
        @Id
        @GeneratedValue(strategy = GenerationStrategy.UNIQUE)
        private String id;
    
        private String fullName;
    
        private String phoneNumber;
    
        private String address;
    
        private Date registrationDate;
    
        private boolean isBusiness;
    
        private String status;
    
        private Tariff currentTariff;
    
        private BillingAccount billingAccount;
    
        public Customer(String fullName, String phoneNumber, String address, Date registrationDate, boolean isBusiness, String status, Tariff currentTariff, BillingAccount billingAccount) {
            this.fullName = fullName;
            this.phoneNumber = phoneNumber;
            this.address = address;
            this.registrationDate = registrationDate;
            this.isBusiness = isBusiness;
            this.status = status;
            this.currentTariff = currentTariff;
            this.billingAccount = billingAccount;
        }
    }
    

    After that it worked just fine. Both read and write operations.