TypeMismatchException the provided ID is of a wrong type

special0ne picture special0ne · Feb 27, 2012 · Viewed 35.5k times · Source

While working on my first app in Hibernate. While trying to retrieve a User object from the DB i am getting the following exception:

org.hibernate.TypeMismatchException: Provided id of the wrong type for class org.cw.form.User. Expected: class java.lang.Integer, got class java.lang.String at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:109) at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:906) at org.hibernate.impl.SessionImpl.load(SessionImpl.java:823) at org.hibernate.impl.SessionImpl.load(SessionImpl.java:816)

I have created the USERS table with the following postgreSQL:

CREATE SEQUENCE user2_id_seq; 

CREATE TABLE USERS(id integer NOT NULL DEFAULT nextval('user2_id_seq'), user_name   varchar(45) NOT NULL UNIQUE , password varchar(45) NOT NULL, email varchar(45) NOT NULL, PRIMARY KEY (id));

And the User entity is defined as such:

@Entity @Table(name="USERS") public class User {

@Id
@Column(name="ID")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;

@Column(name="USER_NAME", unique = true)
private String userName;

@Column(name="PASSWORD")
private String password;

@Column(name="EMAIL")
private String email; .. all the getters and setters...

I am I missing something?

Answer

Jan Papenbrock picture Jan Papenbrock · Aug 1, 2016

I had a different culprit creating this issue: I had copy-pasted another entity's repository which used a String as primary key type.

So I had

class MyEntity implements Serializable {

    @Id
    Integer id

in combination with

interface MyEntityRepository extends CrudRepository<MyEntity, String> {

which produced the error message.

Simply changing the interface type from String to Integer resolved the issue for me.