Home > Back-end >  Spring Boot : mapping between entity and database not working.(Getting {} in response body)
Spring Boot : mapping between entity and database not working.(Getting {} in response body)

Time:02-13

I'm trying to create a webservice but when I try to get records from database(MariaDB), the response is being shown as {} and does not show the actual fields.The code is as below.
(Imports are hidden)
Customer.java


@AllArgsConstructor

@Data
@Entity
@Table(name ="customer")
public class Customer {
    @Id
    @Column(name="customer_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    Long customerId;

    @Column(name = "acc_holder_name")
    String accHolderName;

    @Column(name = "clear_balance")
    Long clearBalance;

    @Column(name = "over_draft")
    Boolean overDraft;

    public Customer() {}

    public Customer(Long id)
    {
        this.customerId = id;
        this.accHolderName = "default";
        this.clearBalance = (long) 0;
        this.overDraft = false;
    }

    public String toString()
    {
        return this.customerId   this.accHolderName;
    }

    public Customer(String accHolderName, long clearBalance, boolean overDraft)
    {
        this.accHolderName = accHolderName;
        this.clearBalance = clearBalance;
        this.overDraft = overDraft;
    }
}

CustomerService.java


@Service
public class CustomerService {
    private CustomerRepository customerRepo;
    
    @Autowired
    public CustomerService(CustomerRepository cr)
    {
        this.customerRepo = cr;
    }
    
    public List<Customer> getCustomers(){
        List<Customer> ls = customerRepo.findAll();
        return ls;
    }
    
}

CustomerController.java



@RestController
@RequestMapping("customer")
public class CustomerController {
    private CustomerService custService;
    
    @Autowired
    public CustomerController(CustomerService cs)
    {
        this.custService = cs;
    }
    @GetMapping
    @ResponseBody
    public List<Customer> getCustomers() {
        return custService.getCustomers();
    }
}

application.properties

spring.datasource.url=jdbc:mariadb://localhost:3306/sample-db
spring.datasource.username=hidden
spring.datasource.password=hidden
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.hibernate.ddl-auto = update

CustomerRepostitory.java

@Repository
public interface CustomerRepository extends JpaRepository<Customer,Long> {
    
}

My table is follows

 ----------------- ------------- ------ ----- --------- ---------------- 
| Field           | Type        | Null | Key | Default | Extra          |
 ----------------- ------------- ------ ----- --------- ---------------- 
| customer_id     | int(11)     | NO   | PRI | NULL    | auto_increment |
| acc_holder_name | varchar(40) | YES  |     | NULL    |                |
| clear_balance   | int(11)     | YES  |     | NULL    |                |
| over_draft      | tinyint(1)  | YES  |     | NULL    |                |
 ----------------- ------------- ------ ----- --------- ---------------- 

My table has 6 records inserted. I send the following request

curl --location --request GET 'localhost:8080/customer/' \
--data-raw ''

And get the following response

[
    {},
    {},
    {},
    {},
    {},
    {}
]

CodePudding user response:

It seems it can't serialize the JSON to the output, so you can add @JsonProperty("variable") into all variables in Customer object, like this:

public class Customer {

    @Id
    @Column(name="customer_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @JsonProperty("customerId")
    Long customerId;

    @Column(name = "acc_holder_name")
    @JsonProperty("accHolderName")
    String accHolderName;

    @Column(name = "clear_balance")
    @JsonProperty("clearBalance")
    Long clearBalance;

    @Column(name = "over_draft")
    @JsonProperty("overDraft")
    Boolean overDraft;
   
    // ...

}

CodePudding user response:

Don’t expose your JPA entities in your Rest API. It is a bad practice. Exposing your entities creates a strong coupling between your API and your persistence model. Therefore use DTO(Data Transfer Object) to return your data. you can use model mapper to map Entity to DTO as bellows.

@Data
public class CustomerDTO {

    Long customerId;

    String accHolderName;

    Long clearBalance;

    Boolean overDraft;
}

use bellow dependency to your pom.xml to get model mapper.

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>2.4.5</version>
</dependency>

then map an entity to DTO as follows.

public List<CustomerDTO> getCustomers(){
    List<CustomerDTO> ls = customerRepo.findAll()
                          .stream()
                          .map(customer-> 
                               new ModelMapper().map(page, SimpleBaseDTO.class))
                          .collect(Collectors.toList());

    return ls;
}
  • Related