javaland235
javaland235

Reputation: 803

Spring Data JPA JpaRepository only uses No Arg Constructor

I have this simple REST API that i created with Spring Boot.

In this app, I have a a POJO called Expense with 4 fields. I have a no Argument constructor and another constructor that takes only two inputs. One String value "item" and one Integer value "amount". The date is set using the LocalData.now() method and the id is set automatically in a MySql db running in the server.

Here's my Entity class

@Entity
public class Expense {
    @Id
    @GeneratedValue (strategy = GenerationType.AUTO)
    private Integer id;
    private String date;
    private String item;
    private Integer amount;

    //No Arg Construction required by JPA
    public Expense() {
    }

    public Expense(String item, Integer amount) {
        this.date = LocalDate.now().toString();
        this.item = item;
        this.amount = amount;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }
}

I have another class with RestController annotation where i have set a method to post Expense object with a post method using Request Mapping annotation.

@RestController
public class ExpController {

    private ExpService expService;
    private ExpenseRepo expenseRepo;

    @Autowired
    public ExpController(ExpService expService, ExpenseRepo expenseRepo) {
        this.expService = expService;
        this.expenseRepo = expenseRepo;
    }


    @RequestMapping(path = "/addExp", method=RequestMethod.POST)
    public void addExp(Expense expense){
        expenseRepo.save(expense);
  }    
}

Now finally i am using PostMan to make the HTTP Post Request. I have made a simple Json Format text to send Item and Amount

    {
        "item":"Bread",
        "amount": 75
    }

After I make the post request, all i can see is that a new Entry is created but all values are set to null.

I have done some experimentation and found out that the expenseRepo.save(expense) method is only using the default no Arg constructor to save the data. But it's not using the second constructor that takes the two parameters that I am passing through Postman

How to solve this issue. Please help

Upvotes: 0

Views: 589

Answers (1)

pvpkiran
pvpkiran

Reputation: 27078

Change your controller method like this

@RequestMapping(path = "/addExp", method=RequestMethod.POST)
public void addExp(@RequestBody Expense expense){
        expenseRepo.save(expense);
}   

You need to use @RequestBody

Upvotes: 1

Related Questions