I have a user object defined as such
@Entity
@Table(name = "user_account")
public class User {
public enum Role {
CLIENT,
ADMIN
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "username",nullable = false)
private String username;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "role", nullable = false)
private Role role;
//setters and getters
}
I have added the role column of the table as type "role" by running the query
CREATE TYPE role AS ENUM('CLIENT', 'ADMIN');
This is the body of my post request:
{
"username": "a",
"password": "your_strong_password",
"role": "CLIENT"
}
I get an error of "org.postgresql.util.PSQLException: ERROR: column "role" is of type role but expression is of type smallint Hint: You will need to rewrite or cast the expression."
The exact line that throws the error is the return statement from saveUser method
public User createUser(User user) {
user.setRole(User.Role.CLIENT.toString());
return userRepository.save(user); //throws error here
}
Why does this error occur (i don't see any places I use "smallint")? If I'm using the wrong approach, please suggest an alternative. thanks
To be able to persist enums you need to specify whether they should be persisted by their ORDINAL (1
, 2
, etc) which is the default or as their text value. Since it seems like you want to use text value in database just add @Enumerated(EnumType.STRING)
:
@Enumerated(EnumType.STRING)
private Role role;
See this article for more info