我试图上传excel文件,然后保存到产品数据库,我有用户,产品表,但产品Map用户表。所以我尝试上传时出错了。
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column "USER_ID"; SQL statement:
因为我需要检查谁上传了文件。测绘是必要的。我不知道应该把Map用户ID的代码放在哪里。
@PostMapping("/api/excel/upload/")
public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file){
String message = "";
if (ExcelHelper.hasExcelFormat(file)){
try{
excelService.save(file);
message = "upload suceed: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
e.printStackTrace();
}
}
message = "please upload file";
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
@Service
public class ExcelService {
@Autowired
ProductRepository repository;
public void save(MultipartFile file){
try{
List<Product> excelEntities = ExcelHelper.excelToExcelEntity(file.getInputStream());
repository.saveAll(excelEntities);
}catch (IOException e){
throw new RuntimeException("failed" + e.getMessage());
}
编辑文章##
@EntityScan
@Entity
@ApiModel
public class Product extends BaseEntity {
@Id
@GeneratedValue
@Column(name = "product_id")
private Long id;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY,optional = false)
@JoinColumn(name = "user_id")
private User user;
我添加了excelentity!
public static List<Product> excelToExcelEntity(InputStream inputStream) {
try {
Workbook wb = new XSSFWorkbook(inputStream);
Sheet sheet = wb.getSheet(SHEET);
Iterator<Row> rows = sheet.iterator();
List<Product> entities = new ArrayList<Product>();
int rowNumber = 0;
while (rows.hasNext()) {
Row currentRow = rows.next();
// skip header
if (rowNumber == 0) {
rowNumber++;
continue;
}
Iterator<Cell> cellsInRow = currentRow.iterator();
Product excelEntity = new Product();
DataFormatter formatter = new DataFormatter();
int cellIdx = 0;
while (cellsInRow.hasNext()) {
Cell currentCell = cellsInRow.next();
1条答案
按热度按时间ohtdti5x1#
您应该能够在控制器中使用以下代码来获取登录用户的用户详细信息。