Spring 启动 Hibernate 多对一不保存 joinColumn 结果
Spring Boot Hibernate Many To One not saving joinColumn result
我正在尝试使用 Spring 引导将图像存储在 MySQL 中,我有一个用户实体,我想在我的 FileUpload 实体之间创建多对一关系。
我在前端使用 React,此上传服务的目的是让用户可以自己设置个人资料图片,但我首先想弄清楚用户和 FileUpload 实体之间的关系是否正确。
我遇到的问题是 FileUpload table 中的 joinColumn 在用户上传图像时不保存用户实体 ID。它只是 returns 外键字段中的空值。
FileUpload.java
@Entity
@Table(name="file_upload")
public class FileUpload {
@Id
@GenericGenerator(name = "uuid", strategy = "uuid2")
@GeneratedValue(generator = "uuid")
private String id;
private String name;
private String type;
@Lob
private byte[] data;
@ManyToOne
@JoinColumn( name="user_id")
private User user;
public FileUpload() {
}
public FileUpload(String name, String type, byte[] data) {
this.name = name;
this.type = type;
this.data = data;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
FileUploadService.java
- 我也有一个存储库,里面没有自定义方法。
@Service
public class FileUploadService {
@Autowired
private FileUploadRepository fileUploadRepository;
public FileUpload store(MultipartFile file) throws IOException {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
FileUpload fileDB = new FileUpload(fileName, file.getContentType(), file.getBytes());
return fileUploadRepository.save(fileDB);
}
public FileUpload getFile(String id) {
return fileUploadRepository.findById(id).get();
}
public Stream<FileUpload> getAllFiles() {
return fileUploadRepository.findAll().stream();
}
}
FileUploadController.java
@Controller
@CrossOrigin()
public class FileUploadController {
@Autowired
private FileUploadService fileUploadService;
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file")MultipartFile file) {
String message = "";
try {
fileUploadService.store(file);
message = "Uploaded the file successfully: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ApiResponse(true, message));
} catch (Exception e) {
message = "Could not upload the file: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ApiResponse(true, message));
}
}
@GetMapping("/files")
public ResponseEntity<List<?>> getListFiles() {
List<FileUploadResponse> files = fileUploadService.getAllFiles().map(dbFile -> {
String fileDownloadUri = ServletUriComponentsBuilder
.fromCurrentContextPath()
.path("/files/")
.path(dbFile.getId())
.toUriString();
return new FileUploadResponse(
dbFile.getName(),
fileDownloadUri,
dbFile.getType(),
dbFile.getData().length);
}).collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.OK).body(files);
}
@GetMapping("/files/{id}")
public ResponseEntity<byte[]> getFile(@PathVariable String id) {
FileUpload fileUpload = fileUploadService.getFile(id);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileUpload.getName() + "\"")
.body(fileUpload.getData());
}
}
邮递员POST请求
MySQL 表格
用户
文件上传
我与确认令牌实体有相同的关系,我必须确认用户电子邮件,该电子邮件确实与 ManyToOne 关系正常工作,但事实并非如此。我正在使用相同的关系映射,但它为我提供了空值,如上所示。
@ManyToOne
@JoinColumn( name="user_id")
private User user;
我可以很好地上传文件,但我希望能够跟踪用户及其文件。
您需要为该实体分配一个用户:
FileUpload fileDB = new FileUpload(fileName, file.getContentType(), file.getBytes());
fileDB.setUser(userThatSentImage); // you need to set user
return fileUploadRepository.save(fileDB);
你们如何对用户进行身份验证?如果您使用 spring 安全性,您可以在此处找到如何从会话中检索用户:https://www.baeldung.com/get-user-in-spring-security
我正在尝试使用 Spring 引导将图像存储在 MySQL 中,我有一个用户实体,我想在我的 FileUpload 实体之间创建多对一关系。
我在前端使用 React,此上传服务的目的是让用户可以自己设置个人资料图片,但我首先想弄清楚用户和 FileUpload 实体之间的关系是否正确。
我遇到的问题是 FileUpload table 中的 joinColumn 在用户上传图像时不保存用户实体 ID。它只是 returns 外键字段中的空值。
FileUpload.java
@Entity
@Table(name="file_upload")
public class FileUpload {
@Id
@GenericGenerator(name = "uuid", strategy = "uuid2")
@GeneratedValue(generator = "uuid")
private String id;
private String name;
private String type;
@Lob
private byte[] data;
@ManyToOne
@JoinColumn( name="user_id")
private User user;
public FileUpload() {
}
public FileUpload(String name, String type, byte[] data) {
this.name = name;
this.type = type;
this.data = data;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
FileUploadService.java
- 我也有一个存储库,里面没有自定义方法。
@Service
public class FileUploadService {
@Autowired
private FileUploadRepository fileUploadRepository;
public FileUpload store(MultipartFile file) throws IOException {
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
FileUpload fileDB = new FileUpload(fileName, file.getContentType(), file.getBytes());
return fileUploadRepository.save(fileDB);
}
public FileUpload getFile(String id) {
return fileUploadRepository.findById(id).get();
}
public Stream<FileUpload> getAllFiles() {
return fileUploadRepository.findAll().stream();
}
}
FileUploadController.java
@Controller
@CrossOrigin()
public class FileUploadController {
@Autowired
private FileUploadService fileUploadService;
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file")MultipartFile file) {
String message = "";
try {
fileUploadService.store(file);
message = "Uploaded the file successfully: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ApiResponse(true, message));
} catch (Exception e) {
message = "Could not upload the file: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ApiResponse(true, message));
}
}
@GetMapping("/files")
public ResponseEntity<List<?>> getListFiles() {
List<FileUploadResponse> files = fileUploadService.getAllFiles().map(dbFile -> {
String fileDownloadUri = ServletUriComponentsBuilder
.fromCurrentContextPath()
.path("/files/")
.path(dbFile.getId())
.toUriString();
return new FileUploadResponse(
dbFile.getName(),
fileDownloadUri,
dbFile.getType(),
dbFile.getData().length);
}).collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.OK).body(files);
}
@GetMapping("/files/{id}")
public ResponseEntity<byte[]> getFile(@PathVariable String id) {
FileUpload fileUpload = fileUploadService.getFile(id);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileUpload.getName() + "\"")
.body(fileUpload.getData());
}
}
邮递员POST请求
MySQL 表格
用户
文件上传
我与确认令牌实体有相同的关系,我必须确认用户电子邮件,该电子邮件确实与 ManyToOne 关系正常工作,但事实并非如此。我正在使用相同的关系映射,但它为我提供了空值,如上所示。
@ManyToOne
@JoinColumn( name="user_id")
private User user;
我可以很好地上传文件,但我希望能够跟踪用户及其文件。
您需要为该实体分配一个用户:
FileUpload fileDB = new FileUpload(fileName, file.getContentType(), file.getBytes());
fileDB.setUser(userThatSentImage); // you need to set user
return fileUploadRepository.save(fileDB);
你们如何对用户进行身份验证?如果您使用 spring 安全性,您可以在此处找到如何从会话中检索用户:https://www.baeldung.com/get-user-in-spring-security