Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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."
like image 758
dubnic Avatar asked Jan 26 '19 12:01

dubnic


1 Answers

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

like image 81
Nazeem Avatar answered Nov 07 '22 00:11

Nazeem