Search code examples
javaspring-data-jpaderby

Spring boot CrudRepository saves bad data


i have problem with saving data in DB.I'm new in Spring Boot. When i run my program the result of writen data is: packagename@randomcode example:com.abc.patient.Patient@6e3e681e

This is my Entity class - Patient.java

@Entity
public class Patient {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;

    // getter, setter, constructor, etc
}

This is my CrudRepo PatientRepository.java

public interface PatientRepository extends CrudRepository<Patient,Integer> {
}

This is my Service class PatientService.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;
    }
}

I think that problem in in the savePatient method in this line:

Patient patients = new Patient(name);

I checked the "name" parameter and it's in 100% correct String. I'm using Derby DB.


Solution

  • The only problem you have is how you are printing out your Patient class. Define a proper toString() or just debug yourself to see the resulting fields. There is no problem in your JPA implementation.

    See this question for the details of default toString