0

In my code i have read an excel sheet and passed the read parameter from excel sheet to method

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

    private MultipartFile uploadfile;

    @Autowired
   private EmployeeRepository employeeRepository;


    @RequestMapping(value = "/upload3", method = RequestMethod.POST, consumes = javax.ws.rs.core.MediaType.MULTIPART_FORM_DATA)
    public void uploadFileHandler(@RequestParam("name") String name,
                                  @RequestParam("file") MultipartFile file) throws IOException {


        this.uploadfile=file;
        System.out.println("*****************************");

        System.out.println("file.getOriginalFilename() " + file.getOriginalFilename());
        System.out.println("file.getContentType()" + file.getContentType());
        System.out.println("file.getInputStream() " + file.getInputStream());
        System.out.println("file.toString() " + file.toString());
        System.out.println("file.getSize() " + file.getSize());
        System.out.println("name " + name);
        System.out.println("file.getBytes() " + file.getBytes());
        System.out.println("file.hashCode() " + file.hashCode());
        System.out.println("file.getClass() " + file.getClass());
        System.out.println("file.isEmpty() " + file.isEmpty());


        try {
            ExcelController ex=new ExcelController();
            File f1=ex.convert(file);
       //     FileInputStream file = new FileInputStream(new File("E://Imp/Details.xlsx"));
            XSSFWorkbook workbook = new XSSFWorkbook(f1);
            XSSFSheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            rowIterator.next();
            while(rowIterator.hasNext())
            {
                Row row = rowIterator.next();
                //For each row, iterate through each columns
                Iterator<Cell> cellIterator = row.cellIterator();

                while(cellIterator.hasNext())
                {
                    Cell cell = cellIterator.next();
                    //This will change all Cell Types to String
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    switch(cell.getCellType())
                    {
                        case Cell.CELL_TYPE_BOOLEAN:
                            System.out.println("boolean===>>>"+cell.getBooleanCellValue() + "\t");
                            break;
                        case Cell.CELL_TYPE_NUMERIC:

                            break;
                        case Cell.CELL_TYPE_STRING:

                            List list=new ArrayList();
                            list.add(cell.getStringCellValue());

                            break;
                    }


                }
                name=row.getCell(0).getStringCellValue();
                String empid = row.getCell(1).getStringCellValue();
               String add=row.getCell(2).getStringCellValue();
              String  mobile=row.getCell(3).getStringCellValue();
                System.out.println(name+empid+add+mobile);
                ExcelController3 ex1=new ExcelController3();
             //   ex1.InsertRowInDB(name,empid,add,mobile);

                System.out.println("");
                Employee em=new Employee();

                em.setName(name);
                em.setEmpid(empid);
                em.setAddress(add);
                em.setMobile(mobile);
                System.out.println(em);
                System.out.println(em.getAddress());
                System.out.println(em.getEmpid());
                System.out.println(em.getMobile());
                System.out.println(em.getName());
                ex1.InsertRowInDB(name,empid,add,mobile,em);

            }
            workbook.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
    }
    public void InsertRowInDB(String name,String empid,String add,String mobile,Employee em) {

//        System.out.println("name "+name);
//        System.out.println("empid "+empid);
//        System.out.println("add "+add);
//        System.out.println("mobile "+mobile);
//        Employee em=new Employee();
//
//        em.setName(name);
//        em.setEmpid(empid);
//        em.setAddress(add);
//        em.setMobile(mobile);
//        System.out.println(em);
//        System.out.println(em.getAddress());
//        System.out.println(em.getEmpid());
//        System.out.println(em.getMobile());
//        System.out.println(em.getName());


     employeeRepository.save(em);

//employeeRepository.save(em);
//        Statement stmt=db.con.createStatement();
//        PreparedStatement ps=null;
//        String sql="Insert into Employee(Name,EmployeeId,Address,ContactInfo) values(?,?,?,?)";
//        ps=db.con.prepareStatement(sql);
//        ps.setString(1, name);
//        ps.setString(2, empid);
//        ps.setString(3, add);
//        ps.setString(4, mobile);
//        ps.executeUpdate();

        System.out.println("Values Inserted Successfully");
    }



    public File convert(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        convFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }


    @GetMapping(value="/upload")
    public ResponseEntity<Collection<Employee>> getallemployees(){
        Collection<Employee> el =employeeRepository.findAll();
        return new ResponseEntity<Collection<Employee>>(el, HttpStatus.OK);
    }
}

But it gives me null pointer exception at employeeRepository.save(em); . unable to find out reason i have autowired employeeRepository also and created proper pojo class for jpa.

7
  • could you also add the definition of employeeRepository? Commented May 3, 2017 at 9:59
  • Wrap your code with try catch and please provide the full error stack. Commented May 3, 2017 at 9:59
  • 1
    Possible duplicate of What is a NullPointerException, and how do I fix it? Commented May 3, 2017 at 10:43
  • Please post the full code of the class showing your @Autowired and class annotation if any. I think that the class is probably not managed by spring (so no @Autowired) Commented May 3, 2017 at 11:02
  • A wild guess!! Your repository employeeRepository is not managed/discoverable by Spring. Check out the packages that are available for scanning. Commented May 3, 2017 at 11:13

2 Answers 2

1

So after reading your code again, the issue is because you use some "new" on your controller. This: ExcelController3 ex1=new ExcelController3(); creates a brand new instance of ExcelController3 that is not managed (i.e. no @Autowired or any other spring magic) and so the repository of ex1 is null.

You probably want to replace:

ExcelController3 ex1=new ExcelController3();
ex1.InsertRowInDB(name,empid,add,mobile,em);

by

this.InsertRowInDB(name,empid,add,mobile,em);

Also note that you should not store some uploaded file (private MultipartFile uploadfile;) on the controller (because every user use the same controller instance)


Some reading:

Sign up to request clarification or add additional context in comments.

Comments

0

I dont know JPA but before you use "employeeRepository.save(em);" dont you need to make a new instance of the class "EmployeeRepository" before you use the function in the class? I can see you declare the class at the top as private EmployeeRepository employeeRepository;

But cant see where you create an instance of it and if you don't it will give you a nullpointer exception error when you try using the function save.

for example:

EmployeeRepository employeeRepository =  new EmployeeRepository ();
employeeRepository.save(em);

If this does not solve your answer please post more detail of function "save"

2 Comments

EmployeeRepository is a interface and it is a jpa repository which provides inbuilt function to save entity object.
Ok I understand thanks for clearing that up, the error suggests that employeeRepository is null so I don't think the annotation or or auto part is working.. So not sure why JPA not seeing or discovering it, Could you put in a try catch and give a stack trace maybe someone can help if they see more info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.