2015-07-09 34 views
0

我需要上传使用下面的表单数据为2个数据库表(工厂和factoryType),但它不是工作有人可以看看:上传文件数据到数据库中使用Spring MVC和休眠

Factory table:factoryId,factoryname 
FactoryType table: factoryType,factoryTypeId 
FactoryConf table: factoryID,factoryTypeId 

我们使用hibernate进行数据库操作。

型号:

@Entity 
@Table(name = "FactoryConf", uniqueConstraints = { 
     @UniqueConstraint(columnNames = { "factoryId" }) 
}) 
public class FactoryConf { 

    @Id 
    long factoryId; 

    @OneToOne 
    @JoinColumn(name = "factoryId", insertable = false, updatable = false) 
    Factory factory; 

    @ManyToOne(optional = false) 
    @JoinColumn(name = "factoryTypeId") 
    FactoryType factoryType; 

    public FactoryConf() { 
     super(); 
    } 

    public FactoryConf(long factoryId, FactoryType factoryType) { 
     super(); 
     this.factoryType = factoryType; 
     this.factoryId = factoryId; 
    } 

    public Factory getFactory() { 
     return factory; 
    } 

    public void setFactory(Factory factory) { 
     this.factory = factory; 
    } 

    public FactoryType getFactoryType() { 
     return factoryType; 
    } 

    public void setFactoryType(FactoryType factoryType) { 
     this.factoryType = factoryType; 
    } 

    public long getFactoryId() { 
     return factoryId; 
    } 

    public void setFactoryId(long factoryId) { 
     this.factoryId = factoryId; 
    } 

    public FactoryType getFactoryTypeByFactoryID(long factoryId){ 
     return factoryType; 
    } 
} 

Bean类:

/** 
* This bean is defined to parse each record from the CSV file. 
* All records are mapped to instances of this bean class. 
* 
*/ 
public class FactoryCSVFileInputBean { 
    private String upload_id; 
    private String file_name; 
    private byte file_data; 
    private long Id; 
    private String Name; 
    private String Type; 

//getter setters  
} 

CSV解析:

/** 
* This class is defined for following actions 
* 1. Validate the input CSV file format, header columns. 
* 2. Parse the CSV file into a list of beans. 
* 3. Validate input records with missing data and prepare a valid factory list to be processed. * 
*/ 
public class FactoryCSVUtil { 
    private static Log log = LogFactory.getLog(FactoryCSVUtil.class); 
    private static final List<String> fileHeaderFields = new ArrayList<String>(); 
    private static final String UTF8CHARSET = "UTF-8"; 
    static{ 
     for (Field f : FactoryCSVFileInputBean.class.getDeclaredFields()) { 
      fileHeaderFields.add(f.getName()); 
     }    
    } 

    public static List<FactoryCSVFileInputBean> getCSVInputList(InputStream inputStream){ 
     CSVReader reader = null; 
     List<FactoryCSVFileInputBean> csvList = null; 
     FactoryCSVFileInputBean inputRecord = null; 
     String[] header = null;   
     String[] row = null; 

     try { 
      reader = new CSVReader(new InputStreamReader(inputStream,UTF8CHARSET)); 
      csvList = new ArrayList<FactoryCSVFileInputBean>(); 
      header = reader.readNext(); 
      boolean isEmptyLine = true; 
      while ((row = reader.readNext()) != null) { 
       isEmptyLine = true; 
       if(!(row.length==1 && StringUtils.isBlank(row[0]))){//not an empty line, not even containing ',' 
        inputRecord = new FactoryCSVFileInputBean(); 
        isEmptyLine = populateFields(inputRecord, header, row);  
        if(row.length != header.length) 
         //inputRecord.setUploadStatus("Not Loaded - Missing or invalid Data"); 

        if(!isEmptyLine) 
         csvList.add(inputRecord); 
       } 
      }      
     } catch (IOException e) { 
      log.debug("IOException while accessing FactoryCSVFileInputBean: " + e); 
      return null; 
     } catch (IllegalAccessException e) { 
      log.debug("IllegalAccessException while accessing FactoryCSVFileInputBean: " + e); 
      return null; 
     } catch (InvocationTargetException e) { 
      log.debug("InvocationTargetException while copying FactoryCSVFileInputBean properties: " + e); 
      return null; 
     } catch (Exception e) { 
      log.debug("Exception while parsing CSV file: " + e); 
      return null; 
     }finally{ 
      try{ 
       if(reader!=null) 
        reader.close(); 
      }catch(IOException ioe){} 
     } 

     return csvList; 
    } 


    protected static boolean populateFields(FactoryCSVFileInputBean inputRecord,String[] header, String[] row) throws IllegalAccessException, InvocationTargetException { 
     boolean isEmptyLine = true; 
     for (int i = 0; i < row.length; i++) { 
      String val = row[i]; 

      if(!StringUtils.isBlank(val)){ 
       BeanUtilsBean.getInstance().copyProperty(inputRecord, header[i], val); 
       isEmptyLine = false; 
      } else { 
       //inputRecord.setUploadStatus(String.format("Not Loaded - Missing or invalid Data for:%s",header[i])); 
      } 
     } 

     return isEmptyLine; 
    } 


    public static void validateInputFile(CommonsMultipartFile csvFile, Model model){ 
     InputStream inputStream = null; 
     CSVReader reader = null; 
     String fileName = csvFile.getOriginalFilename(); 
     String fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1); 
     if(fileExtension.toUpperCase().equals("CSV")){ 
      try{ 
       inputStream = csvFile.getInputStream(); 
       reader = new CSVReader(new InputStreamReader(inputStream,UTF8CHARSET)); 
       String[] header = reader.readNext(); 
       if(header!=null){ 
        for (int i = 0; i < header.length; i++) { 
         if(!header[i].equals("") && !fileHeaderFields.contains(header[i])){ 
          log.debug("Invalid Column found in upload file: " + header[i]); 
          model.addAttribute("failureMsg", "Invalid Column found in upload file: " + header[i]); 
          break; 
         } 
        } 

        for(csvHeaderFieldsEnum field : csvHeaderFieldsEnum.values()){ 
         if(!Arrays.asList(header).contains(field.getValue())){       
          log.debug("Missing column in upload file: " + field.getValue()); 
          model.addAttribute("failureMsg", "Missing column in upload file: " + field.getValue()); 
          break; 
         }       
        } 

       }else{ 
        model.addAttribute("failureMsg", "File is Empty - Please select a valid file");     
       }     
       String[] data = reader.readNext(); 
       if(data==null){ 
        log.debug("Empty file with header - No data found"); 
        model.addAttribute("failureMsg", "Empty file with header - No data found"); 
       }       
      }catch(IOException e){ 
       log.debug("IOException in reading the CSV file: " + e); 
       model.addAttribute("failureMsg", "Exception in reading the CSV file"); 
      }finally{ 
       if(reader!=null) 
        try{ 
         reader.close();  
        }catch(IOException e){ log.debug("IOException in closing reader of CSV file: " + e);} 
      } 
     } 
     else{ 
      model.addAttribute("failureMsg", "Invalid file format - Please select a CSV file"); 
     }  

    } 
} 

型号

public class FactoryUploadForm { 
    private CommonsMultipartFile fileData; 
    private String uploadComment; 
    /** 
    * @return the fileData 
    */ 
    public CommonsMultipartFile getFileData() { 
     return fileData; 
    } 
    /** 
    * @param fileData the fileData to set 
    */ 
    public void setFileData(CommonsMultipartFile fileData) { 
     this.fileData = fileData; 
    } 
    /** 
    * @return the uploadComment 
    */ 
    public String getUploadComment() { 
     return uploadComment; 
    } 
    /** 
    * @param uploadComment the uploadComment to set 
    */ 
    public void setUploadComment(String uploadComment) { 
     this.uploadComment = uploadComment; 
    } 

    public String toString(){ 
     return " CSVFileName: " + getFileData().getOriginalFilename() + "; Upload Comment: " + uploadComment; 
    } 


} 

控制器

@Controller 公共类FactoryUploadDownloadController {

private static final Log logger = LogFactory.getLog(FactoryUploadDownloadController.class); 

@Resource 
Service Service; 

@Resource 
FactoryUploadRepository repository; 


@RequestMapping(value = "/submitUploadFactoryForm") 
public String uploadFactory(FactoryUploadForm uploadform, 
     HttpServletRequest request, Model model, BindingResult result) { 
    logger.debug("===================================================================="); 

    List<FactoryCSVFileInputBean> csvList = null; 
    List<FactoryType> factoryTypes = Service.getFactoryTypes(); 

    try { 
     CommonsMultipartFile file = uploadform.getFileData(); 
     // parse csv file to list 
     csvList = FactoryCSVUtil.getCSVInputList(file.getInputStream()); 
     if (csvList == null) { 
      model.addAttribute("failureMsg","Error in file parsing - Please verify the file"); 

      logger.debug("---------------------------------------------------------"); 
      return "sucess"; 
     } 

    } catch (Exception e) { 
     logger.debug("sorry this isn't working for you"); 

    } 
    try { 
     CommonsMultipartFile file = uploadform.getFileData(); 

     for (FactoryCSVFileInputBean inputRecord : csvList) { 
      Factory factoryentity = new Factory(); 
      factoryentity.setId(inputRecord.getId()); 
      factoryentity.setName(inputRecord.getName()); 
      factoryentity = this.Service.saveFactory(factoryentity); 

      FactoryConf factoryconf = new FactoryConf(); 
      factoryconf.setFactory(factoryentity); 
      factoryconf.setFactoryType(pickFactoryType(factoryTypes,inputRecord.getType())); 
      model.addAttribute("factoryconf", factoryconf); 

      this.Service.savefactoryCfg(factoryconf); 

     } 

    } catch (Exception e) { 
     logger.debug("sorry this isnt working for you"); 

    } 
    return "success"; 
} 

private FactoryType pickFactoryType(List<FactoryType> types, String typeName) { 

    for (FactoryType type : types) { 
     if (type.getFactoryType().equalsIgnoreCase(typeName)) 
      return type; 
    } 

    throw new RuntimeException(String.format("Factory Type Invalid :%s", typeName)); 
} 

}

+1

“但它没有工作” - 谨慎详细说明?你有没有堆栈跟踪? – DuncanKinnear

+0

另外,您不需要为@ @ Id字段定义'@ UniqueConstraint'。根据定义,它们已经是唯一的。如果表名与实体名相同,则甚至不需要'@ Table'注释。 – DuncanKinnear

+0

你将实体保存到数据库的位置?我可以看到静态的'getCSVInputList'方法解析你的CSV并返回它,但是什么把这个列表保存到实体? – DuncanKinnear

回答

-1

从你的问题,据我所知,你是不是能够解析数据来自CSV文件。 Here是类似任务的示例代码。我认为这应该有所帮助。