1

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.

buræquete
  • 14,226
  • 4
  • 44
  • 89
  • There is no constructor define for this line Patient patients = new Patient(name) in Patient class entity. – GauravRai1512 Nov 08 '18 at 15:22
  • I think that is just because you haven't provided a toString method for your Patients class... the default toString just prints out the name of the class and the memory address. Did you actually inspect it in a debugger? – AHungerArtist Nov 08 '18 at 15:34
  • Maybe you should override `Patient`'s `to_string` method? – Laurenz Albe Nov 08 '18 at 15:34
  • YESSS ! thank You AHungerArtis and Laurenz-Albe ! The problem was in Patient class.I haven't provide toString method. – AmrykanskiKowboy Nov 08 '18 at 15:50

2 Answers2

1

Try:

public void savePatient(Patient patient) {
    patientRepository.save(patient);
}
buræquete
  • 14,226
  • 4
  • 44
  • 89
1

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

buræquete
  • 14,226
  • 4
  • 44
  • 89