Entity or DTO approach for SpringJDBC template?

Viewed 577

I have a Java Batch job which uses plain JDBC to execute lot of queries with lot of joins. I decided to convert the plain JDBC code to Spring JDBC project which uses JDBCTemplate.
Its purely a command line batch program and there is no GUI. There are around 40 tables and 4-5 tables have 300+ columns. I am not sure whether to create Entity classes for those tables or create DTO pojo classes?

I understand that DTO classes are to decouple the entity classes and view. Since I do not have GUI and I am dealing with only DB with lot of handmade queries with joins , is it better to use only entity classes instead of DTO classes ? I'm not using JPA , instead I am using spring JDBC.

So the code looks like

 List<Customer> customers = jdbcTemplate.query(
                sql,
                new BeanPropertyRowMapper(Customer.class));

Here the Customer should be a Entity class or DTO? Please advise.

2 Answers

The traditional approach is:

  1. Use CustomerEntity on the @Repository level.

  2. Use CustomerDto on the @Service level.

In your case I would prefer to use:

  1. CustomerEntity — if it corresponds to a CUSTOMERS table row. CustomerEntity can have relations, for example List<OrderEntity>.

  2. For aggregate data (select query with multiple joins) CustomerReportDto can be used (or just CustomerReport).

  3. CustomerResponse for an endpoint response.

I would suggest to use Both.

Use Entity for db operation like insert,update etc...

Use DTO for passing data from REST API to Service or Service to REST API. For this you need to use converter for DTO to ENTITY and ENTITY to DTO at service level. Sometime it happens that from front or REST API, we will be getting some extra information which may need for some calculation but not for DB so in that case it is good to use DTO and ENTITY.

Related