5

I'm trying to develop a simple CRUD-application,that receives data in the JSON-format,processes it, and puts it in a PostgreSQL table. One of the fields in the table, gender, is represented by an enumeration.

Here I am trying to add an entry using the Postman:

{
    "employeeId": 1,
    "firstName": "Ada",
    "lastName": "Lovelace",
    "departmentId": 3,
    "jobTitle": "Senior",
    "gender": "FEMALE",
    "dateOfBirth": "1815-12-10"
}

Here is the DAO-layer code:

@Override
public void addEmployee(Employee employee) {
    String sql = "INSERT INTO employees(employee_id, first_name, last_name, department_id, job_title, gender, date_of_birth) VALUES (?, ?, ?, ?, ?, CAST(? AS gender), ?)";
    getJdbcTemplate().update(sql, employee.getEmployeeId(), employee.getFirstName(), employee.getLastName(),
            employee.getDepartmentId(), employee.getJobTitle(), employee.getGender(), employee.getDateOfBirth());
}

As a result, I get: 500 Internal Server Error and

"PreparedStatementCallback; bad SQL grammar [INSERT INTO employees(employee_id, first_name, last_name, department_id, job_title, gender, date_of_birth) VALUES (?, ?, ?, ?, ?, CAST(? AS gender), ?)]; nested exception is org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of com.way.dto.Gender. Use setObject() with an explicit Types value to specify the type to use."
2
  • This has already been answered. Besides, you should also post the database model for the employee's table. Jan 26, 2019 at 13:05
  • I saw this question and the article indicated in the answer helped me in a similar situation. Thank you for responding.
    – dubnic
    Jan 26, 2019 at 13:24

1 Answer 1

8

What SQL type is the gender field?

In stead of passing in the enum, you could also pass in the string equivalent, for example employee.getGender().name() or employee.getGender().toString()

2
  • 1
    When creating the table, I created the type "gender" as an enumeration ... Everything works, thanks a lot
    – dubnic
    Jan 26, 2019 at 13:23
  • 2
    it's common for SQL wrappers to be confused by enums, stringing them is the easiest fix.
    – Jasen
    Jan 27, 2019 at 8:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.