Can I directly map the data from an external source on it to persist on DB?

AndreaNobili :

I am pretty new in Spring Data JPA and ORM in general. I have the following architectural doubt.

Lets consider this entity class:

@Entity // This tells Hibernate to make a table out of this class
public class Order {

   @Id
   @GeneratedValue(strategy=GenerationType.AUTO)
   private int id;

   @Column(name = "name")
   private String fullName;
   private String address;
   private String product;

   @Column(name = "order_date_time")
   private String orderDate;

   private Double quantity;

   // getters, setters 
}

This class is mapped on my order database table.

In my application data came from an Excel document that I parse via Apace POI and than I have to persist on the database. My doubt is: can I directly use this entity class to map an Excel row using Apache POI in order to persist the Excel rows as order table records? Or is better to use another DTO class to read the rows from Excel and than use this DTO to set the field values of my entity class?

An entity class can contain a constructor using fields?

v.ladynev :

From architectural point of view better to have a DTO class and encapsulate some logic there.

class CsvOrder {

    private String fullName;

    private String address;

    public CsvRecord(String[] record) {
        fullName = get(record, FULLNAME_INDEX);
        address = get(record, ADDRESS_INDEX);
    }

    public Order toOrder() {
        Order result = new Order();

        result.setFullName(fullName);

        return result;
    }

}

public static <T> T get(T[] arr, int index) {
    final T notFound = null;
    return index < size(arr) ? arr[index] : notFound;
}

public static <T> int size(T[] array) {
    return array == null ? 0 : array.length;
}

You can put a static method toOrder() to OrderServiceMapper, if you want to totally decouple layers

class OrderServiceMapper {

    public static Order toOrder(CsvOrder order) {
        Order result = new Order();

        result.setFullName(order.getFullName());

        return result;
    }

}

Also, use Integer in place of int for id. Better to use Long everywhere

    // This tells Spring to add this class to Hibernate configuration during auto scan
    @Entity 
    public class Order {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;

    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=350282&siteId=1