How to fix "Can't infer the SQL type to use for an instance of enum" error when inserting enum value?

Vladislav :

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."

Please help me, I google this problem for several days and I can not find a solution

Nazeem :

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()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=101649&siteId=1