Skip to content
Advertisement

Update DB column which has null value in Spring boot JPA

I am trying to update in the database with the help of the Spring JPA and having an issue while doing it. I have an Embedded class in my entity. My entity class is :

@Entity
@Data
public class Users extends AbstractEntity {
    private String name;
    private String email;
    private Audit audit;
    private TransferDetails transferDetails;
    private BeneficiaryDetails beneficiaryDetails;
}

My Repository class is :

public interface UserRepo extends JpaRepository<Users, Long> {
}

Audit, Transfer and Beneficiary Details are my Emededded class and those are :

@Embeddable
@Data
public class Audit {
    private String createdBy;
    private Date createdDate;
}
@Data
@Embeddable
public class BeneficiaryDetails {
    private String BeneficiaryName;

    public String getBeneficiaryName() {
        return BeneficiaryName;
    }

    public void setBeneficiaryName(String beneficiaryName) {
        BeneficiaryName = beneficiaryName;
    }
}
@Data
@Embeddable
public class TransferDetails {
    @Column(name = "TransferCurrency")
    private String TransferCurrency;
    private String ChequeCurrency;
}

My Controller class is:

@RestController
@RequestMapping("/api/v1/Users")
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserRepo userRepo;

    @GetMapping("/users/{id}")
    public ResponseEntity<Users> getTutorialById(@PathVariable("id") long id) {
        Optional<Users> userData = userRepo.findById(id);

        if (userData.isPresent()) {
            return new ResponseEntity<>(userData.get(), HttpStatus.OK);
        } else {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    @PostMapping(path = "/saveData", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Users> createTutorial(@RequestBody Users users) {
        try {
            LOGGER.info("Starting to save the form.....");
            return new ResponseEntity<>(userRepo.save(users), HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Transactional
    @PutMapping("/updateData/{id}")
    public ResponseEntity<Users> updateTutorial(@PathVariable("id") long id, @RequestBody Users users) {
        try {
            Optional<Users> userRepoById = userRepo.findById(id);
            LOGGER.info("Starting to update the form.....");
            if (userRepoById.isPresent()) {
                Users _users = userRepoById.get();
                _users.setName(users.getName());
                _users.setEmail(users.getEmail());
                _users.setAudit(users.getAudit());
                LOGGER.info("getTransferCurrency --> " + users.getTransferDetails().getTransferCurrency());
                LOGGER.info("getChequeCurrency --> " + users.getTransferDetails().getChequeCurrency());
                **_users.getTransferDetails().setTransferCurrency(users.getTransferDetails().getTransferCurrency());**
                LOGGER.info("getBeneficiaryName --> " + users.getBeneficiaryDetails().getBeneficiaryName());
                _users.getBeneficiaryDetails().setBeneficiaryName(users.getBeneficiaryDetails().getBeneficiaryName());
                return new ResponseEntity<>(userRepo.save(_users), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            String str = "";
            for (int i = 0; i < (e.getStackTrace().length); i++)
                str = str + e.getStackTrace()[i] + " <br> ";
            System.out.println("EXP MSG: " + str);
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}

My error stack trace is :

sa.project.sabb.controller.UserController.updateTutorial(UserController.java:60)  
sa.project.sabb.controller.UserController$$FastClassBySpringCGLIB$$c1b6e8ae.invoke(<generated>)  
 org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)  
 org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779)  
 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)  
 org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)  
 org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)  
 org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)  
 org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)  
 org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)  
 org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)  
 org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692)  
 sa.project.sabb.controller.UserController$$EnhancerBySpringCGLIB$$51f2328.updateTutorial(<generated>)  
 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)  
 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)  
 java.lang.reflect.Method.invoke(Method.java:498)  
 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)  
 org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)  
 org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)  
 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)  
 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)  
 org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)  
 org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1064)  
 org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)  
 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)  
 org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:920)  
 javax.servlet.http.HttpServlet.service(HttpServlet.java:684)  
 org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)  
 javax.servlet.http.HttpServlet.service(HttpServlet.java:764)  
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)  
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)  
 org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)  
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)  
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)  
 org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)  
 org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)  
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)  
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)  
 org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)  
 org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)  
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)  
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)  
 org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)  
 org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)  
 org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)  
 org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)  
 org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)  
 org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)  
 org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)  
 org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)  
 org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)  
 org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)  
 org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)  
 org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)  
 org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)  
 org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)  
 org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1726)  
 org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)  
 org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)  
 org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)  
 org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)  
 java.lang.Thread.run(Thread.java:748)  

What I understand is that I have some null values in the columns of DB and I am trying to update them. Is there something I am missing? Could someone me help in this regard? Any help will be much appreciated. Thanks

Advertisement

Answer

Have you tried this?

TransferDetails td = users.getTransferDetails();
if(td != null) {
    TransferDetails _td = _users.getTransferDetails();
    if(_td != null) {
        _td.setTransferCurrency(td.getTransferCurrency());
    } else {
        _td = new TransferDetails();
        _td.setTransferCurrency(td.getTransferCurrency());
        _users.setTransferDetails(_td);
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement