0

i am currently developing a backend API with help of Spring Boot Project.

The POST request which i am sending from postman to one of the resource method in Controller class. But all the data is showing as null

Entity class

public class SIM_Entity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String Sim_card_no;
    private String Mobile_no;
    private boolean status;
    @Temporal(TemporalType.DATE)
    private Date Expiry_date;
    private boolean State_of_registration;
    private String KYC;
    private String Telecom_Provider;
    private String Full_Name;

    /**
     * @param sim_card_no
     * @param mobile_no
     * @param status
     * @param expiry_date
     * @param state_of_registration
     * @param kYC
     * @param telecom_Provider
     * @param full_Name
     */
    public SIM_Entity(String sim_card_no, String mobile_no, boolean status, Date expiry_date,
            boolean state_of_registration, String kYC, String telecom_Provider, String full_Name) {
        super();
        Sim_card_no = sim_card_no;
        Mobile_no = mobile_no;
        this.status = status;
        Expiry_date = expiry_date;
        State_of_registration = state_of_registration;
        KYC = kYC;
        Telecom_Provider = telecom_Provider;
        Full_Name = full_Name;
    }

    /**
     * 
     */
    public SIM_Entity() {

    }

    public Long getId() {
        return id;
    }

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

    public String getSim_card_no() {
        return Sim_card_no;
    }

    public void setSim_card_no(String sim_card_no) {
        Sim_card_no = sim_card_no;
    }

    public String getMobile_no() {
        return Mobile_no;
    }

    public void setMobile_no(String mobile_no) {
        Mobile_no = mobile_no;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public Date getExpiry_date() {
        return Expiry_date;
    }

    public void setExpiry_date(Date expiry_date) {
        Expiry_date = expiry_date;
    }

    public boolean isState_of_registration() {
        return State_of_registration;
    }

    public void setState_of_registration(boolean state_of_registration) {
        State_of_registration = state_of_registration;
    }

    public String getKYC() {
        return KYC;
    }

    public void setKYC(String kYC) {
        KYC = kYC;
    }

    public String getTelecom_Provider() {
        return Telecom_Provider;
    }

    public void setTelecom_Provider(String telecom_Provider) {
        Telecom_Provider = telecom_Provider;
    }

    public String getFull_Name() {
        return Full_Name;
    }

    public void setFull_Name(String full_Name) {
        Full_Name = full_Name;
    }

    @Override
    public String toString() {
        return "SIM_Entity [id=" + id + ", Sim_card_no=" + Sim_card_no + ", Mobile_no=" + Mobile_no + ", status="
                + status + ", Expiry_date=" + Expiry_date + ", State_of_registration=" + State_of_registration
                + ", KYC=" + KYC + ", Telecom_Provider=" + Telecom_Provider + ", Full_Name=" + Full_Name + "]";
    }

}

Controller class

@RestController
@RequestMapping(value = "/")
public class SIMCardController {

    @Autowired
    private SIMCardService simCardService;

    @GetMapping
    public String SIMCardManagement_Message() {
        return "Welcome to SIM Card Management Application Development";
    }

    @PostMapping(value = "/add", consumes = "application/json", produces = "application/json")
    public ResponseEntity<SIM_Entity> saveSIM_Entity(@RequestBody SIM_Entity entity) {
        System.out.println("The value of Entity coming from Client request :"+" "+entity.toString());
        try {
            SIM_Entity createSIMCardEntry = simCardService.createSIMCardEntry(entity);
            return new ResponseEntity<>(createSIMCardEntry, HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping(value = "/listall", consumes = "application/json", produces = "application/json")
    public ResponseEntity<List<SIM_Entity>> getAllEntity() {
        try {
            List<SIM_Entity> allSimCardEntry = simCardService.getAllSimCardEntry();
            return new ResponseEntity<List<SIM_Entity>>(allSimCardEntry, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
        }

    }

    @PutMapping(value = "/{id}")
    public ResponseEntity<SIM_Entity> updateSimCardInfo(@PathVariable("id") Long id, @RequestBody SIM_Entity entry) {
        SIM_Entity updateSimEntryRecord = simCardService.updateSimEntryRecord(id, entry);
        return new ResponseEntity<SIM_Entity>(updateSimEntryRecord, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<HttpStatus> deleteSIMById(@PathVariable("id") Long id) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

}

Error Stack Trace

/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.2)

2022-08-16 05:55:51.394  INFO 61555 --- [  restartedMain] c.t.SimCardReStBackEndApiApplication     : Starting SimCardReStBackEndApiApplication using Java 11.0.12 on Bikashs-MacBook-Air.local with PID 61555 (/Users/bikashmohapatra/SpringRest_Workspace/SIM_Card_ReST_BackEnd_API/target/classes started by bikashmohapatra in /Users/bikashmohapatra/SpringRest_Workspace/SIM_Card_ReST_BackEnd_API)
2022-08-16 05:55:51.396  INFO 61555 --- [  restartedMain] c.t.SimCardReStBackEndApiApplication     : No active profile set, falling back to 1 default profile: "default"
2022-08-16 05:55:51.444  INFO 61555 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-08-16 05:55:51.444  INFO 61555 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-08-16 05:55:52.360  INFO 61555 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-08-16 05:55:52.468  INFO 61555 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 86 ms. Found 1 JPA repository interfaces.
2022-08-16 05:55:53.181  INFO 61555 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2022-08-16 05:55:53.190  INFO 61555 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-08-16 05:55:53.191  INFO 61555 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.65]
2022-08-16 05:55:53.264  INFO 61555 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-08-16 05:55:53.264  INFO 61555 --- [  restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1819 ms
2022-08-16 05:55:53.465  INFO 61555 --- [  restartedMain] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-08-16 05:55:53.495  INFO 61555 --- [  restartedMain] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.6.10.Final
2022-08-16 05:55:53.606  INFO 61555 --- [  restartedMain] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-08-16 05:55:53.673  INFO 61555 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2022-08-16 05:55:54.053  INFO 61555 --- [  restartedMain] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2022-08-16 05:55:54.064  INFO 61555 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2022-08-16 05:55:54.562  INFO 61555 --- [  restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-08-16 05:55:54.568  INFO 61555 --- [  restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-08-16 05:55:54.931  WARN 61555 --- [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2022-08-16 05:55:55.240  INFO 61555 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2022-08-16 05:55:55.275  INFO 61555 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2022-08-16 05:55:55.287  INFO 61555 --- [  restartedMain] c.t.SimCardReStBackEndApiApplication     : Started SimCardReStBackEndApiApplication in 4.384 seconds (JVM running for 5.5)
2022-08-16 05:57:24.474  INFO 61555 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-08-16 05:57:24.476  INFO 61555 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-08-16 05:57:24.493  INFO 61555 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 17 ms

    The value of Entity coming from Client request : SIM_Entity [id=null, Sim_card_no=null, Mobile_no=null, status=true, Expiry_date=null, State_of_registration=false, KYC=null, Telecom_Provider=null, Full_Name=null]

2022-08-16 05:57:24.813  WARN 61555 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1048, SQLState: 23000
2022-08-16 05:57:24.813 ERROR 61555 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'mobile_no' cannot be null
2022-08-16 05:57:24.814  INFO 61555 --- [nio-8080-exec-1] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements

how to resolve this issue?

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Are the keys of the json request matching with the property/setters names of the Java class? – admlz635 Aug 16 '22 at 00:48
  • Well , yes the keys are exactly matching with property/setters name. { "Sim_card_no": "2476254U", "Mobile_no": "9581961264", "status": true, "Expiry_date": "2022-08-16", "State_of_registration": null, "KYC": "Updated", "Telecom_Provider": "Airtel", "Full_Name": "Bikash Mohapatra" } – Bikash Mohapatra Aug 16 '22 at 00:52
  • Still i am not able to resolve the issues.Other resource methods are working fine except "/add". – Bikash Mohapatra Aug 16 '22 at 00:53
  • 1
    might be a [duplicate](https://stackoverflow.com/questions/15303110/jackson-json-field-mapping-capitalization). try to follow java naming convention (field should start with a lower case letter) or use `@JsonProperty` on your setters and getters with the name of your field which start with upper case – Andrei Titov Aug 16 '22 at 07:18
  • Does this answer your question? [Jackson JSON field mapping capitalization?](https://stackoverflow.com/questions/15303110/jackson-json-field-mapping-capitalization) – admlz635 Aug 16 '22 at 22:21

1 Answers1

0

I reproduced the bug and got the same problem. I was able to solve it. Firstly as Andrew Thomas said you should follow the java naming convention (camelCase). Secondly, if you want to continue with the property names that you have declared take a look at your parameterized constructor . Whatever name you are accepting in that constructor and whatever name you are passing from the front-end should always match. In your case, they don't match that's why those fields are not getting populated with the required data.

I would suggest you use a DTO class along with a library called Lombok which will take care of everything

For getters, setters and constructors you can use like this

@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class SIM_Entity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String Sim_card_no;
    private String Mobile_no;
    private boolean status;
    @Temporal(TemporalType.DATE)
    private Date Expiry_date;
    private boolean State_of_registration;
    private String KYC;
    private String Telecom_Provider;
    private String Full_Name;

    /**
     * @param sim_card_no
     * @param mobile_no
     * @param status
     * @param expiry_date
     * @param state_of_registration
     * @param kYC
     * @param telecom_Provider
     * @param full_Name
     */
    public SIM_Entity(String sim_card_no, String mobile_no, boolean status, Date expiry_date,
                      boolean state_of_registration, String kYC, String telecom_Provider, String full_Name) {
        super();
        Sim_card_no = sim_card_no;
        Mobile_no = mobile_no;
        this.status = status;
        Expiry_date = expiry_date;
        State_of_registration = state_of_registration;
        KYC = kYC;
        Telecom_Provider = telecom_Provider;
        Full_Name = full_Name;
    } 
Akhil
  • 59
  • 1
  • 11