在一列中使用“获取空值”;findById“;在JavaSpring中,尽管它存在于DB中
我对JavaSpring非常陌生,有一个问题,我无法找出我缺少了什么 为了简洁起见,我将把它缩短:在一列中使用“获取空值”;findById“;在JavaSpring中,尽管它存在于DB中,java,angular,spring,jpa,Java,Angular,Spring,Jpa,我对JavaSpring非常陌生,有一个问题,我无法找出我缺少了什么 为了简洁起见,我将把它缩短: 我有一个控制器类,它有两个方法用于@GetMapping(从数据库中的患者获取信息)和@PostMapping(从该患者上传照片) 在这两种方法中,在某个时刻,我通过“findById”调用数据库并填充“Patient”模型类对象 该类的所有属性都已从数据库中成功检索,但该类的一个属性(getPhoto())仅在@PostMapping方法中获取空值 我错过了什么?这两种方法的代码完全相同 非
- 我有一个控制器类,它有两个方法用于@GetMapping(从数据库中的患者获取信息)和@PostMapping(从该患者上传照片)
- 在这两种方法中,在某个时刻,我通过“findById”调用数据库并填充“Patient”模型类对象
- 该类的所有属性都已从数据库中成功检索,但该类的一个属性(getPhoto())仅在@PostMapping方法中获取空值
- 我错过了什么?这两种方法的代码完全相同
@CrossOrigin(origins="http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping({"/patients"})
public class PatientController {
@Autowired
IPatientService patientService;
@GetMapping("/{id}")
public ResponseEntity<?> listPatientId(@PathVariable("id") Integer id){
Optional<Patient> patient=null;
Map<String, Object> response=new HashMap<>();
try{
patient=patientService.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
/*Some other code*/
}
@PostMapping("/upload")
public ResponseEntity<?> upload(@RequestParam("archive")MultipartFile archive, @RequestParam("id") Integer id){
Optional<Paciente> paciente = Optional.empty();
Map<String, Object> respuesta= new HashMap<>();
try{
patient=patientService.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
/*Some other code*/
}
}
package question.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import question.repository.Patient;
import question.repository.PatientsRepository;
@CrossOrigin(origins="http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping("/patients")
public class PatientController {
private PatientsRepository patientsRepository;
@Autowired
public PatientController(PatientsRepository patientsRepository) {
this.patientsRepository = patientsRepository;
}
@GetMapping("/{id}")
public ResponseEntity<?> listPatientId(@PathVariable("id") Integer id){
Optional<Patient> patient=null;
Map<String, Object> response=new HashMap<>();
try{
patient = patientsRepository.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
return ResponseEntity.ok(patient);
}
@PostMapping(value="/upload")
public ResponseEntity<?> upload(@RequestParam("archive") MultipartFile archive, @RequestParam("id") Integer id){
Optional<Patient> patient = Optional.empty();
Map<String, Object> response = new HashMap<>();
try{
patient = patientsRepository.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
return ResponseEntity.ok(patient);
}
}
存储库:
@Repository
public interface PatientRepository extends JpaRepository<Patient, Integer> {
Iterable<Patient> findByNameContainingOrSurnameContaining(String name, String surname);
}
package question.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PatientsRepository extends CrudRepository<Patient, Integer>{
}
服务:
constructor(private http:HttpClient, private router:Router) {
this.urlPatients='http://localhost:8080/patients';
}
uploadPhoto(file: File, id):Observable<Patient>{
let formData= new FormData();
formData.append("archive", file);
formData.append("id", id);
return this.http.post(`${this.urlPatients}/upload`, formData).pipe(
map((response:any)=> response.patient as Patient),
catchError(e=>{
console.error(e.error.mensaje);
return throwError(e);
})
);
}
构造函数(专用http:HttpClient,专用路由器:路由器){
这是我的http://localhost:8080/patients';
}
上传照片(文件:文件,id):可观察{
设formData=new formData();
formData.append(“存档”,文件);
formData.append(“id”,id);
返回this.http.post(`${this.urlPatients}/upload`,formData).pipe(
map((应答:任意)=>response.patient作为患者),
捕捉错误(e=>{
控制台错误(e.error.mensaje);
回击投手(e);
})
);
}
更新:
使用邮递员并向http://localhost:8080/patients/upload 在主体中发送了一个jpg文件(表单数据-“归档”)和一个id号(“id”),我成功地插入了内容,而以前在后端无法使用的方法(patient.get().getPhoto())这次运行得非常好。使用相同的代码,所以我假设这是@BiteBat所说的,这是前端的问题,以及它如何调用后端的问题。我模拟了您创建的相同环境,正如您所期望的,它对我有效,我将代码留给您来检查您的问题所在。我认为您调用POST方法是错误的。现在,我建议您不要将图像保存在关系数据库中,因为还有性能更好的替代方案,例如Google存储/本地存储或任何文件存储服务 结构: 入口点:
package question;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
@EnableJpaRepositories
public class JulianPelayoApplication {
public static void main(String[] args) {
SpringApplication.run(JulianPelayoApplication.class, args);
}
}
控制器:
@CrossOrigin(origins="http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping({"/patients"})
public class PatientController {
@Autowired
IPatientService patientService;
@GetMapping("/{id}")
public ResponseEntity<?> listPatientId(@PathVariable("id") Integer id){
Optional<Patient> patient=null;
Map<String, Object> response=new HashMap<>();
try{
patient=patientService.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
/*Some other code*/
}
@PostMapping("/upload")
public ResponseEntity<?> upload(@RequestParam("archive")MultipartFile archive, @RequestParam("id") Integer id){
Optional<Paciente> paciente = Optional.empty();
Map<String, Object> respuesta= new HashMap<>();
try{
patient=patientService.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
/*Some other code*/
}
}
package question.controller;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import question.repository.Patient;
import question.repository.PatientsRepository;
@CrossOrigin(origins="http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping("/patients")
public class PatientController {
private PatientsRepository patientsRepository;
@Autowired
public PatientController(PatientsRepository patientsRepository) {
this.patientsRepository = patientsRepository;
}
@GetMapping("/{id}")
public ResponseEntity<?> listPatientId(@PathVariable("id") Integer id){
Optional<Patient> patient=null;
Map<String, Object> response=new HashMap<>();
try{
patient = patientsRepository.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
return ResponseEntity.ok(patient);
}
@PostMapping(value="/upload")
public ResponseEntity<?> upload(@RequestParam("archive") MultipartFile archive, @RequestParam("id") Integer id){
Optional<Patient> patient = Optional.empty();
Map<String, Object> response = new HashMap<>();
try{
patient = patientsRepository.findById(id);
}catch(DataAccessException e){
response.put("error", e.getMessage().concat(": "+e.getMostSpecificCause().toString()));
new ResponseEntity<Map<String, Object>>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
System.out.println("Patient with id: "+id+" / "+patient.get().getId()+" which photo is: "+patient.get().getPhoto());
return ResponseEntity.ok(patient);
}
}
Spring.properties:
spring.datasource.url=jdbc:postgresql://localhost/test
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
Pom:
4.0.0
org.springframework.boot
职位
注意,您可以简单地使用@PathVariable(“id”)Patient-Patient
。但是,您是否调试了控制器并确保id
的值与您期望的值相符?您在两个catch block中都错过了“return”语句谢谢您的回答。是的,我确保值id在两种方法中都是正确的。。。虽然我的示例中缺少return语句,但在实际代码中我提供了它。非常感谢您对BiteBat的回复。虽然它对我很有用,但我无法解决获取照片字符串名称的问题(patient.get().getPhoto())。我会继续努力,一旦我发现我的错误,我会把它贴在这里。也谢谢你的推荐!您能告诉我们您是如何使用或调用该方法的吗?您还可以显示服务类和存储库类,这些类中也可能有错误。很抱歉@BiteBat延迟了响应。我再次编辑了我的问题,插入了存储库和服务类。以及前端(角度)中调用方法的部分。我使用了Postman,一切都很完美,所以我假设这是如您所说的,问题与Angular有关,而不是JavaSpring代码。
@Entity
@Table(name = "patients", schema = "business")
@Getter @Setter
public class Patient {
@Id
@Column
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column
private String photo;
}
spring.datasource.url=jdbc:postgresql://localhost/test
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>question</groupId>
<artifactId>JulianPelayo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>JulianPelayo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>