I would like to apologize in advance if this question has been answered before.
Please note that the project is using Spring Boot, Jackson and Hibernate.
Anyway, I forked a project by Jasenko Hadziomeragic. I wanted to know how he was able to save an object, in Jasenko's project, the Product object. In this project, the Product object looks like this (please note that I removed parts of the code to focus on the foreign key) :
@JoinColumn(name = "member_id")
@NotNull
private Long member_id;
I can save a new record by using this JSON:
{
"name" : "Product 2",
"member_id" : "1"
}
This works but from what I have scoured in the internet, it's better to use this instead:
public class Product {
@ManyToOne()
@JoinColumn(name="member_id")
private Member member;
/* A getter/setter for the memeber id*/
public Long getMember_id() {
return this.member.getId();
}
public void setMember_id(Long member_id) {
this.member.setId(member_id);
}
}
I tried to save a new record with the same json above, I get this error:
java.lang.NullPointerException: null
at com.jersey.representations.Product.setMember_id(Product.java:100)
Here's a link to my github that contains modified codes.
I also checked this SO question that is similar to my concern. But what it does it first it sends a select query first to populate the Member object. But that means before I save a record, I have to request another select statement. It's a bit of an overhead, isn't it?
UPDATE I added this code in the constructor:
public Product() {
this.member = new Member();
}
I did fix my issue but is this the correct way of dealing with my concern?
UPDATE 2
What I am trying to avoid is sending this JSON:
[
{
"id": 1,
"name": "Derp",
"currency": "599",
"regularPrice": 1203,
"discountPrice": 59,
"member": {
"id": 1,
"firstName": "Paul",
"lastName": "Andrews",
"email": "myemail@email.com"
}
},
{
"id": 2,
"name": "Another product ",
"currency": "909",
"regularPrice": 1203,
"discountPrice": 59,
"member": {
"id": 1,
"firstName": "Paul",
"lastName": "Andrews",
"email": "myemail@email.com"
}
},
{
"id": 3,
"name": "Another product 1",
"currency": "909",
"regularPrice": 1203,
"discountPrice": 59,
"member": {
"id": 1,
"firstName": "Paul",
"lastName": "Andrews",
"email": "myemail@email.com"
}
}
]
As you can see, the member keeps repeating whereas I can just send the memberId.