How to add new fields / values to an existing entity in Spring Data JPA

Viewed 617

How can I add new fields or values or properties to an existing entity and store them in the same table?

Customer entity already exists and have fields as

 - id
 - name
 - lastName

Want to add contactNumber (as seen in the api structure below) to this existing Customer entity. Don't want a new entity for contactNumber The expected request body is as below:

{
    "id": "int auto generated",
    "name": "String",
    "lasName": "String",
    "contactNumber":
    {
        "mobile":"long",
        "office":"long",
        "home":"long"
    }
}

How can this be achieved ? Checked some blogs related to mapstruct but not getting proper solution.

1 Answers

You can use @Embeddable :

@Embeddable
public class ContactNumber {
    private Long mobile;
    private Long office;
    private Long home;
    // getters, setters...
}

Customer Entity:

@Entity
public class Customer {
    @Id
    private Long id;
    private String name;
    private String lastName;

    @Embedded
    private ContactNumber contactNumber;
    // getters, setters...
}

With this mapping three columns(mobile, office, home) will be added to the Customer table.

You can simply save the Customer with the request body in the question using (@RequestBody Customer customer) parameter:

@PostMapping(value="/customers")
public void saveCustomers(@RequestBody Customer customer) {
    customerRepository.save(customer);
}

For more information take a look at here.

Related