I’m trying to upload excel file then save it to Product DB, I have User, Product Tables but product mapped by user Table. so I got error when I try to upload.
x
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column "USER_ID"; SQL statement:
Since I need to check who upload the file. mapping is nessesary. I don’t know where should I put the code to map the userId.
@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());
}
Editted post ##
@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;
I added the 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();
Advertisement
Answer
You should be able to use the below code in your controller to get UserDetails of the logged in user.
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();