Home > database >  class com.bank.model.Account cannot be cast to class java.lang.Double (com.bank.model.Account is in
class com.bank.model.Account cannot be cast to class java.lang.Double (com.bank.model.Account is in

Time:03-20

while calling method account/balance/{accountNumbe} I got Typecasting error, please help me to resolve this problem as soon as possible. I am providing that error that I have got while calling that method through the postman

I could not understand what was happening exactly please give a solution as soon as possible.

My AccountService and controller is

    package com.bank.service;
    
    import java.util.List;
    
    import java.util.Optional;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Service;
    
    import com.bank.model.Account;
    import com.bank.repository.AccountRepository;
    import com.bank.Exception.ResourceNotFoundException;
    
    @Service
    public class AccountService {
    
        @Autowired
        AccountRepository accountRepository;
        
        public Account findAccountById(int accountNumber) {
            
            return accountRepository.getById(accountNumber);
        }
        
        public List<Account> accountByType(String accountType) {
             List<Account> x= accountRepository.findByAccountType(accountType);
             return x;
        }
        
        public String deleteById(int accountNumber) {
            
            Optional<Account> account=accountRepository.findById(accountNumber);         
            if(!(account.isEmpty())) {
                accountRepository.deleteById(accountNumber);
                return "deleted";
            }else {
                return "Account [accountId=" accountNumber "] can't be found";
            }
            
        }
        
        public String deleteAllAccounts() {
            accountRepository.deleteAll();
            return "all Accounts are deleted";
        }
        
        
        public String getBalanceById(int accountNumber) {
          String balance=Double.toString(accountRepository.getBalanceByaccountNumber(accountNumber));
          Optional<Account> account=accountRepository.findById(accountNumber);
          if(account.isPresent()) {
                  return balance;
          }else {
              return "Invalid accountNumber";
          }
        }
        
        public Account updateAccount(int accountNumber,Account account) {
            Optional<Account> acc=accountRepository.findById(accountNumber);
            if(acc.isPresent()) {
                Account a1=acc.get();
                a1.setAccountNumber(account.getAccountNumber());
                a1.setAccountType(account.getAccountType());
                a1.setBalance(account.getBalance());
                
                return accountRepository.save(a1);
            }else {
                return null;
            }
        }
        
        public Account accountCreate(Account account) {
            return accountRepository.save(account);
        }
        
        public List<Account> allAccounts(){
            List<Account> accountList=accountRepository.findAll();
            return accountList;
        }
        
        public ResponseEntity<?> transferFunds(int from,int to,double amount){
            
            Account fromAccount=accountRepository.getById(from);
            Account toAccount=accountRepository.getById(to);
            
            if(fromAccount==null) {
                throw new ResourceNotFoundException("account [accountNumber=" from "] can't be found");
            }
            if(toAccount==null) {
                throw new ResourceNotFoundException("account [accountId=" to "] can't be found");
            }
            else if (fromAccount.getBalance()>amount) {
                fromAccount.setBalance(fromAccount.getBalance()-amount);
                toAccount.setBalance(toAccount.getBalance() amount);
                accountRepository.save(fromAccount);
                accountRepository.save(toAccount);
               return new ResponseEntity<>("Account balance has been updated successfully in the following accounts" " " from "and" " " to " ",HttpStatus.OK);
            }
            else {
             throw new ResourceNotFoundException("acoount[" from "]  does not have the enough balance");
            }
            
        }
        
        public ResponseEntity<?> deposite(double amount,int accountNumber)  {
            Account account=accountRepository.getById(accountNumber);
            if(account==null) {
                throw new ResourceNotFoundException("account [accountNumber=" accountNumber "] can't be found");
            }else {
            account.setBalance(account.getBalance() amount);
            accountRepository.save(account);
            return new ResponseEntity<>("Sucessfully deposited",HttpStatus.OK);
        }
        }
      
        public ResponseEntity<?> withdraw(double amount, int accountNumber) {
            Account account=accountRepository.getById(accountNumber);
            if(account==null) {
                throw new ResourceNotFoundException("account [accountNumber=" accountNumber "] can't be found");
            }else if(account.getBalance()<amount) {
                  throw new ResourceNotFoundException("Insufficient balance!!!");
            }else {
            account.setBalance(account.getBalance()-amount);
            accountRepository.save(account);
            return new ResponseEntity<>("withdrwa successully done!!",HttpStatus.OK);
        }
        }
        
        
        
    }

my Accountcontroller is

package com.bank.controller;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bank.model.Account;
import com.bank.service.AccountService;
import com.bank.Exception.ResourceNotFoundException;

@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    AccountService accountService;
    
    @PostMapping
    public ResponseEntity<?> createAccount(@RequestBody Account account){
        Account acc=accountService.accountCreate(account);
        if(acc!=null) {
            return new ResponseEntity<>(acc,HttpStatus.CREATED);
        }else {
        throw new ResourceNotFoundException("account not created!!");
        }   
    }
    
    @GetMapping("/aclist")
    public ResponseEntity<?> accountList(){
        
        List<Account> accountList=accountService.allAccounts();
        if(!(accountList.isEmpty())) {
            return new ResponseEntity<>(accountList,HttpStatus.OK);
        }else {
            throw new ResourceNotFoundException("accounts not found");
        }
        
    }
    
    @GetMapping("/byType/{accountType}")
    public ResponseEntity<?> byAccountType(@PathVariable String accountType){
        List<Account> account =accountService.accountByType(accountType);
        if(account.isEmpty()) {
            throw new ResourceNotFoundException(accountType "" "Type of account does not exist!!");
        }else {
            return new ResponseEntity<>(account,HttpStatus.OK);
        }
    }
    
    @GetMapping("/{accountNumber}")
    public ResponseEntity<?> getAccountById(@PathVariable("accountNumber") int accountNumber){
        Account acc=accountService.findAccountById(accountNumber);
        if(acc!=null) {
            return new ResponseEntity<>(acc,HttpStatus.OK);
        }else {
            throw new ResourceNotFoundException("account [accountNumber=" accountNumber "] can't be found");
        }
    }

    @PutMapping("/{from}/{to}/{amount}")
    public ResponseEntity<?> transferFunds(@PathVariable("from") int from,@PathVariable("to") int to,@PathVariable("amount") double amount){
        return accountService.transferFunds(from, to, amount);  
    }
    
    @DeleteMapping("/{accountNumber}")
    public ResponseEntity<?> deleteAccById(@PathVariable ("accountNumber") int accountNumber){
        String x=accountService.deleteById(accountNumber);
        if(x.equalsIgnoreCase("deleted")){
            return new ResponseEntity<>("deleted successfully",HttpStatus.OK);
        }else {
            throw new ResourceNotFoundException("Account [accountNumber=" accountNumber "] can't be find");
        }
    }
    
    @GetMapping("/balance/{accountNumber}")
    public ResponseEntity<?> getBalanceById(@PathVariable ("accountNumber") int accountNumber){
        String balance=accountService.getBalanceById(accountNumber);
        
        if(balance.equalsIgnoreCase("Invalid accountNumber")) {
            throw new ResourceNotFoundException("Account [accountNumber=" accountNumber "] can't be found");
            
        }else {
            return new ResponseEntity<>(balance,HttpStatus.OK);
        }
    }
    
    @DeleteMapping("/deleteAll")
    public ResponseEntity<?> deleteAllAccounts(){
        return new ResponseEntity<>(accountService.deleteAllAccounts(),HttpStatus.OK);
    }   

    @PutMapping("/update/{accountNumber}")
    public ResponseEntity<?> UpdateAccount(@PathVariable ("accountNumber") int accountNumber,@RequestBody Account account){
        Account acc=accountService.updateAccount(accountNumber, account);
        if(acc!=null) {
            return new ResponseEntity<>(acc,HttpStatus.OK);
        }else {
            throw new ResourceNotFoundException("invalid accountNumber and account");
        }
    }
    
    @PutMapping("/deposite/{amount}/{accountNumber}")
    public ResponseEntity<?> deposite(@PathVariable("amount") double amount,@PathVariable("accountNumber") int accountNumber){
        
        return accountService.deposite(amount,accountNumber);
    }
    @PutMapping("/withdraw/{amount}/{accountNumber}")   
    public ResponseEntity<?> withDraw(@PathVariable("amount") double amount,@PathVariable("accountNumber") int accountNumber){
        return accountService.withdraw(amount,accountNumber);
    }
    
    
    
}
    

MY Accountrepository is

package com.bank.repository;

import java.util.List;


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.bank.model.Account;

@Repository
public interface AccountRepository  extends JpaRepository<Account,Integer>{

    List<Account> findByAccountType(String accountType);
    double getBalanceByaccountNumber(int accountNUmber);
    
    
    
    
}

I have got the below error

java.lang.ClassCastException: class com.bank.model.Account cannot be cast to class java.lang.Double (com.bank.model.Account is in unnamed module of loader 'app'; java.lang.Double is in module java.base of loader 'bootstrap') at jdk.proxy2/jdk.proxy2.$Proxy115.getBalanceByaccountNumber(Unknown Source) ~[na:na] at com.bank.service.AccountService.getBalanceById(AccountService.java:51) ~[classes/:na] at com.bank.controller.AccountController.getBalanceById(AccountController.java:88) ~[classes/:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na] at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.16.jar:5.3.16] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.16.jar:5.3.16] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.16.jar:5.3.16] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.16.jar:5.3.16] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.16.jar:5.3.16] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.16.jar:5.3.16] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.16.jar:5.3.16] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.16.jar:5.3.16] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.16.jar:5.3.16] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.16.jar:5.3.16] at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.58.jar:4.0.FR] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.16.jar:5.3.16] at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.58.jar:4.0.FR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.58.jar:9.0.58] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.16.jar:5.3.16] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.16.jar:5.3.16] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96) ~[spring-boot-actuator-2.6.4.jar:2.6.4] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.16.jar:5.3.16] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117) ~[spring-web-5.3.16.jar:5.3.16] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.58.jar:9.0.58] at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]

My model classes are account model class

'''
package com.bank.model;

import javax.persistence.CascadeType;


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.Proxy;

@Entity
@Table(name="Account")
@Proxy(lazy = false)
public class Account {

    @Id
    int accountNumber;
    @Column(name="balance")
    Double balance;
    @Column(name="accountType")
    String accountType;
    
    @ManyToOne(targetEntity=Customer.class,cascade = CascadeType.ALL)
    @JoinColumn(name="ca_fk",referencedColumnName = "customerId")
    Customer customer;

    public Account() {
        super();
        
    }

    public Account(int accountNumber, Double balance, String accountType, Customer customer) {
        super();
        this.accountNumber = accountNumber;
        this.balance = balance;
        this.accountType = accountType;
        this.customer = customer;
    }

    @Override
    public String toString() {
        return "Account [accountNumber="   accountNumber   ", balance="   balance   ", accountType="   accountType
                  ", customer="   customer   "]";
    }

    public Integer getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(int accountNumber) {
        this.accountNumber = accountNumber;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    public String getAccountType() {
        return accountType;
    }

    public void setAccountType(String accountType) {
        this.accountType = accountType;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    
    
}

'''

CodePudding user response:

Remove the double getBalanceByaccountNumber(int accountNUmber); query from AccountRepository.java.

@Repository
public interface AccountRepository extends JpaRepository<Account,Integer>{
   List<Account> findByAccountType(String accountType);
}

Change the getBalanceById(int accountNumber) method in AccountService.java

    public String getBalanceById(int accountNumber) {
        Optional<Account> account=accountRepository.findById(accountNumber);
          if(account.isPresent()) {
              return account.get().getBalance();
          } else {
              return "Invalid accountNumber";
        }
   }

Modify in Account.java

public Double getBalance() {
   return balance != null ? balance : 0;
}
  • Related