0

I am having a Spring Data rest API where I am trying to save a new record in Entity named comment. This entity has a many to one relationship with another entity named department.

When I call the post api for this entity , I am getting below null pointer error but I am passing the department foreign key as part of the postman request. I am not sure why it is not getting received in the server side. Can someone please throw some light on it.

Error

   "cause": {
        "cause": {
            "cause": null,
            "message": "ERROR: null value in column \"department_id\" of relation \"comments\" violates not-null constraint\n  Detail: Failing row contains (32, null, null, null, null, null)."
        },
        "message": "could not execute statement"
}

Comment Entity (Removed getters and setters for saving lines

@Table(name="comments")
public class Comment implements Serializable {
    private static final long serialVersionUID = 1L;

    
    @Id
    @SequenceGenerator(name="SEQUENCE_FOR_COMMENTS", sequenceName="SEQUENCE_FOR_COMMENTS",allocationSize = 1 )
    @GeneratedValue(strategy=GenerationType.AUTO, generator="SEQUENCE_FOR_COMMENTS")
    @Column(name="comment_id")
    private Integer commentId;

    private String comment;

    @ManyToOne
    @JoinColumn(name="department_id")
    private Department department;


}

Department Entity (Removed getters and setters for saving lines

public class Department implements Serializable { private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO, generator="SEQUENCE_FOR_Department" )
@Column(name="department_id")
private Long departmentId;

}

Postman Request

{
"departmentv1":{
    "departmentId":163
},
"comment":"Apr292023"

}
Saimuga
  • 255
  • 1
  • 5
  • 16

1 Answers1

0

well I think you are first not passing the referencedColumnName what it does is it denotes the relationship between the associated table(department) and current table(comment) in the current table current entity is commentId which is basically a foreign key and an associated table(department) you have your primary key which is missing but I think it is not going to impact this much if you forgot to mention it if they both have the same name

//Entity layer

//like for instance here is an example associated table(categories)

@Table(name = "categories")
public class Categories 
{
@Id
@Column(name = "cat_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotBlank
@Column(name = "cat_name")
private String catName;
}

//and this is current table(subcategories)

@Table(name = "subcategories")
public class SubCategories 
{
@Id
@Column(name = "sub_cat_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotBlank
@Column(name = "sub_cat_name")
private String subCatName;

//it denotes the relationship between current entity(name = "cat_id") in 
present table(Sub_category) with the  referencedColumnName = "cat_id"
present in associated table(Categories)
@JoinColumn(name = "cat_id", referencedColumnName = "cat_id") 
@ManyToOne(fetch = FetchType.LAZY)
private Categories categories;
}

//Repository layer

//Categories

public interface CategoriesRepository extends JpaRepository<Categories, 
Long>
{

}

//SubCategories

public interface SubCategoriesRepository extends 
JpaRepository<SubCategories, Long>
{

}

//Service layer logic

public ResponseEntity<Map<String, Object>> 
addSubCategory(AddSubCategoryRequest addSubCategoryRequest)
{
    SubCategories newSubCategoryCategories = new SubCategories();
    newSubCategoryCategories.setSubCatName(addSubCategoryRequest.
                                           getSubCatName());
 
    newSubCategoryCategories.setCategories(addSubCategoryRequest.
                                           getCategories());
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("data", 
            subCategoriesRepository.save(newSubCategoryCategories));
    map.put(sts, true);
    map.put(msg, "Sub-Category added success");
    return ResponseEntity.ok().body(map);
}

//Controller layer

@PostMapping("/admin/add/sub/category")
public ResponseEntity<Map<String, Object>> addSubCategory(@RequestBody 
@Valid AddSubCategoryRequest subCategory)
{
    return service.addSubCategory(subCategory);
}

//PostMan Request

{
"subCatName":"T-shirts",
"categories":{
    "id":1,
    "catName":"Clothing and fashion"
}
}

and I can see one more thing here you are just passing departmentId not other values of the department table hope this example will solve your problem if not then let me know

  • Hi Sachintha / Alpha, I tried both of your suggestions and modified the postman request as well, Still I am getting the same null pointer error. Not sure what is going wrong here :( Also I have found one more thing, Instead of calling the entity endpoint , if I create a custom controller in the server side (Spring data rest) and call the controller end point, then the request is getting through successfully with the same postman request without any null pointer exception. Very Strange !!! – Saimuga May 01 '23 at 20:25
  • Hi @Saimuga can you provide us more details like your logs(screenshot) and code so it will be easy for us to understand your problem I don't know why you don't want to use controller class to do this thing because in this way you have minimal control like the way you are using – Alpha Momin May 02 '23 at 04:25