Pramay Nikhade
Pramay Nikhade

Reputation: 35

Mapping Multiple Columns to same field of an Object which is part of an Array JPA

I am trying to map an array of Objects to a field. All the fields in that object are being mapped to columns with different name but similar structure. The response structure should be:

 "customers": [
    {
      "firstName": "string",
      "lastName": "string",
      "products": [
        {
            "description":"string",
            "amount": "string"
        },
        {
            "description":"string",
            "amount": "string"
        }
      ]
    }
 ]

Inside the products field, I have a list of product(description and amount). In DB, columns are stored like

product_des1,product_amt1,product_des2,product_amt2.....product_des30,product_amt30

. I need to map these two fields to the product(object). How should I approach to solve the problem using JPA annotations if possible?

For the reference: Customers.class

@Entity
public class Customers implements Serializable {

    @Column(name = "firstName")
    private String firstName;

    @Column(name = "lastName")
    private String lastName;

    @ElementCollection
    List<Products> products;

}

Product.class

@Embeddable
public class Product implements Serializable {

    @Column(?)
    private String description;

    @Column(?)
    private String amount;

}

Upvotes: 0

Views: 2843

Answers (1)

Smutje
Smutje

Reputation: 18123

Inside the products field, I have a list of product(description and amount). In DB, columns are stored like

product_des1,product_amt1,product_des2,product_amt2.....product_des30,product_amt30

So your Products JPA entity should simply look like this:

@Embeddable
public class Products implements Serializable {

    @Column(name = "product_des1")
    private String description1;

    @Column(name = "product_amt1")
    private String amount1;

    @Column(name = "product_des2")
    private String description2;

    @Column(name = "product_amt2")
    private String amount2;

   // ... repeat
}

if you don't want to do additional mapping between the DB and JPA entities (which I don't recommend - I try to keep JPA entities as exact representation of a DB row and map, if necessary, in Java and not between different technologies).

Upvotes: 1

Related Questions