首页 > 解决方案 > 尽管它存在于数据库中,但在 Java Spring 中使用“findById”在一列中获取空值

问题描述

我是 Java Spring 的新手,遇到一个问题,我无法弄清楚我错过了什么。

为了简洁起见,我将简短地说:

首先十分感谢!!

控制器:

@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*/

    }
}

患者等级:

@Entity
@Table(name = "patients")
public class Patient {
    @Id
    @Column
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    @Column
    private String photo;

    (Getters and setters)
}

存储库:

@Repository
public interface PatientRepository extends JpaRepository<Patient, Integer> {

    Iterable<Patient> findByNameContainingOrSurnameContaining(String name, String surname);

}

服务(接口和实现):

public interface IPatientService {

    public List<Patient> findAll();

    public Optional<Patient> findById(Integer id);

    public Iterable<Patient> findByNameContainingOrSurnameContaining(String term);

 }



@Service
public class PatientServiceImpl implements IPatientService {

    @Autowired
    private PatientRepository patientDao; 


    @Override
    @Transactional(readOnly = true)
    public List<Patient> findAll() {
        return patientDao.findAll();
    }


    @Override
    public Optional<Patient> findById(Integer id) {
        return patienteDao.findById(id);
    }

    public Iterable<Patient> findByNameContainingOrSurnameContaining(String term){
        return patientDao.findByNameContainingOrSurnameContaining(term, term);
    }

    @Override
    public Patient save(Patient patient){
        return patientDao.save(patient);
    }

    @Override
    public void deleteById(Integer id) {
        patientDao.deleteById(id);
    }


}

如前所述,“patient.get().getPhoto()”在@GetMapping 中返回存储在数据库中的实际值。但是在使用 @PostMapping 注释的方法中,该值返回 null (尽管其他属性似乎工作得很好)。

这是后端,但在前端我使用的是 Angular,我在组件中调用此方法(我只显示上传照片中涉及的部分):

  patient: Patient;


  constructor(private route: ActivatedRoute, private router: Router, private service: ServiceServicee) {
    this.paient = new Patient();
  }


 uploadPhoto() {
    this.service.uploadPhoto(this.selectedPhoto, 
      this.patient.id).subscribe(patient => {
        this.patient = patient;
      });
  }

服务:


  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://localhost:8080/patients/upload 并在正文中发送一个 jpg 文件(form-data - “archive”)和一个 ID 号(“id”),我得到了一个插入的成功和它以前在后端没有工作的方法(耐心.get().getPhoto())这次完美地工作了。使用相同的代码,所以我假设它就像@BiteBat 所说的那样,这是前端的问题以及它如何调用后端。

标签: javaangularspringjpa

解决方案


我模拟了您创建的相同环境,它按您的预期为我工作,我将代码留给您查看您的问题。我认为您错误地调用了 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);
    }

}

控制器:

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);

    }
    
}

存储库:

package question.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PatientsRepository extends CrudRepository<Patient, Integer>{

}

病人:

@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>

回复:

得到 在此处输入图像描述

邮政 在此处输入图像描述 在此处输入图像描述


推荐阅读