Insert spring boot data to database

I am completely new to spring boot and I am now trying to insert some data to my database from spring boot. What is the correct way to do this?
file structure
NewUser.java

package com.example.demo.pojo;
public class NewUser {
    private String CompanyName;

    public String getCompanyName() {
        return CompanyName;
    }

    public void setCompanyName(String CompanyName) {
        this.CompanyName = CompanyName;
    }
}

RegistrationController.java

package com.example.demo.controller;

import com.example.demo.result.Result;
import com.example.demo.pojo.NewUser;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.service.RegistrationService;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
public class RegistrationController {
    @CrossOrigin
    @PostMapping(value = "api/registration")

    @ResponseBody
    public Result registration(@RequestBody NewUser user) {
        System.out.println(user.toString());
        return new Result(200);
    }


}

Above is how I get data from frontend and below is what I tried to insert data. How should I call the service to insert data?

AccApplMapper.java

package com.example.demo.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface AccApplMapper {
    @Insert("INSERT INTO ACCT_APPL(ENG_COMP_NAME) VALUES(#{CompanyName}")
    public int addAcctAppl(@Param("CompanyName") String CompanyName);
}
 

RegistrationService.java

package com.example.demo.service;

import com.example.demo.mapper.AccApplMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RegistrationService {
    

    private AccApplMapper accApplMapper;
    public int addAcctAppl(String CompanyName) {
        return accApplMapper.addAcctAppl(CompanyName);
    }
}

>Solution :

Based on question above, you can modify your registration method in RegistrationController something like below, along with using Autowired annotation in controller :

public class RegistrationController {
..
@Autowired
RegistrationService registrationService;
...

public Result registration(@RequestBody NewUser user) {
        System.out.println(user.toString());
        if(user!=null && user.getCompanyName()!=null) {
          int insert = registrationService.addAcctAppl(user.getCompanyName());
          return insert>=0 ? new Result(200) : new Result(500);
        }
        else {
          return new Result(400);
       }
    }

here based on input data, calling service method & returning appropriate httpStatus code as argument to Result.

Leave a Reply