42

I have one entity which contains primary key of type string. This entity model is as follows:

@Entity
public class MyEntity {

@Id
@Column(name="PR_KEY", unique=true)
private String prKey;

....
....

}

But I am facing issue saying TypeMismatch.

org.hibernate.TypeMismatchException: Provided id of the wrong type. Expected: class java.lang.String, got class java.lang.Long
Natan Streppel
  • 5,759
  • 6
  • 35
  • 43
Kailas
  • 807
  • 1
  • 6
  • 20

4 Answers4

57

If you don't specify an id generation strategy, Hibernate will use GenerationType.AUTO. This will result in any of

AUTO - either identity column, sequence or table depending on the underlying DB.

If you look here, you'll notice all of those generate ids of type long, short or int, not of type String.

Say you wanted a String UUID as an id, you could use

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
@Column(name = "PR_KEY")
private String prKey;
Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 11
    Value of this key is provided by some other entity in my program. I dont want it to be generated automatically. I think GeneratedValue annotation will make it generated value. Please correct me – Kailas Sep 05 '13 at 21:49
3

Check the PR_KEY data type in database table. This problem might occur, if the column is of type Number and you are trying to map the same to String in your entity.

Same applies to the coulmn with generated Ids.

Gyanendra Dwivedi
  • 5,511
  • 2
  • 27
  • 53
1

A very simple way to use string as primary key by using strategy = "uuid" in the annotation @GenericGenerator(name = "system-uuid", strategy = "uuid")

This will generates a unique 36-character id

@Entity
@Data
@NoArgsConstructor
public class ToDoClass {

    @NotNull
    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;
     
    //...
      
}
Jimmy
  • 995
  • 9
  • 18
0

When String is used as a id, same type should be used also when finding entity via Session/EntityManager:

Instead of providing Long:

Long key = 1L;
MyEntity me = session.get(MyEntity.class, key); 
//or 
MyEntity me = entityManager.find(MyEntity.class, key); 

String should be given:

String key = "1";
MyEntity me = session.get(MyEntity.class, key); 
//or 
MyEntity me = entityManager.find(MyEntity.class, key); 
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135