Search code examples
javamysqljdbcsql2o

retrieve MySQL auto increment in Java


I'm trying to retrieve idPatient from the database but i keep getting errors, idPatient is auto increment. But i don't know if that's what causing the problem.

This is the code i'm trying

public List<Patient> getPatientsFromDatabase() {
    String sql = "SELECT naam, voornaam, gebit, idPatient from patienten";
    try (Connection con = sql2o.open()) {
        return con.createQuery(sql)
                .throwOnMappingFailure(false)
                .executeAndFetch(Patient.class);
    }
}

the DB:

enter image description here

The error:

enter image description here

Edit - Patient:

public Patient(String voornaam, String naam, String gebit, int id) {
    this.voornaam = voornaam;
    this.naam = naam;
    this.id = id;
    if (null != gebit)switch (gebit) {
        case "melkgebit":
            g = new Melkgebit();
            this.gebit = "melkgebit";
            break;
        case "volwassengebit":
            g = new Volwassengebit();
            this.gebit = "volwassengebit";
            break;
        case "wisselgebit":
            this.gebit = "wisselgebit";
            break;
        default:
            break;
    }
}

Solution

  • The mapping between columns and properties are done automatically by name. Of course this is not always possible

    In your case you have defined id (java properties) as idPatient (corresponding column in the database table). The easiest solution for this, is to use aliases in sql queries.

    Try to change your sql:

    SELECT naam, voornaam, gebit, idPatient id from patienten;
    

    For more information visit http://www.sql2o.org/docs/column-mappings/