Spring 启动 CrudRepository 保存坏数据
Spring boot CrudRepository saves bad data
我在 DB.I Spring Boot 的新功能中保存数据时遇到问题。当我 运行 我的程序写入数据的结果是: packagename@randomcode example:com.abc.patient.Patient@6e3e681e
这是我的实体 class - Patient.java
@Entity
public class Patient {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
// getter, setter, constructor, etc
}
这是我的 CrudRepo PatientRepository.java
public interface PatientRepository extends CrudRepository<Patient,Integer> {
}
这是我的服务classPatientService.java
@Service
public class PatientService {
@Autowired
private PatientRepository patientRepository;
public void savePatient (String name) {
Patient patient = new Patient(name);
patientRepository.save(patient);
}
public Optional<Patient> showPatient(int id) {
return patientRepository.findById(id);
}
public List<Patient> showAllPatients() {
List<Patient> patients = new ArrayList<>();
patientRepository.findAll().forEach(patients::add);
return patients;
}
}
我认为问题出在 savePatient
方法这一行:
Patient patients = new Patient(name);
我检查了 "name"
参数,它是 100% 正确的字符串。我正在使用 Derby DB。
尝试:
public void savePatient(Patient patient) {
patientRepository.save(patient);
}
您遇到的唯一问题是如何打印 Patient
class。定义适当的 toString()
或自行调试以查看结果字段。你的JPA实现没有问题。
有关默认 toString
的详细信息,请参阅此 question
我在 DB.I Spring Boot 的新功能中保存数据时遇到问题。当我 运行 我的程序写入数据的结果是: packagename@randomcode example:com.abc.patient.Patient@6e3e681e
这是我的实体 class - Patient.java
@Entity
public class Patient {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
// getter, setter, constructor, etc
}
这是我的 CrudRepo PatientRepository.java
public interface PatientRepository extends CrudRepository<Patient,Integer> {
}
这是我的服务classPatientService.java
@Service
public class PatientService {
@Autowired
private PatientRepository patientRepository;
public void savePatient (String name) {
Patient patient = new Patient(name);
patientRepository.save(patient);
}
public Optional<Patient> showPatient(int id) {
return patientRepository.findById(id);
}
public List<Patient> showAllPatients() {
List<Patient> patients = new ArrayList<>();
patientRepository.findAll().forEach(patients::add);
return patients;
}
}
我认为问题出在 savePatient
方法这一行:
Patient patients = new Patient(name);
我检查了 "name"
参数,它是 100% 正确的字符串。我正在使用 Derby DB。
尝试:
public void savePatient(Patient patient) {
patientRepository.save(patient);
}
您遇到的唯一问题是如何打印 Patient
class。定义适当的 toString()
或自行调试以查看结果字段。你的JPA实现没有问题。
有关默认 toString