1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.