Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @Id with String Type in JPA / Hibernate?

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 
like image 301
Kailas Avatar asked Sep 04 '13 19:09

Kailas


People also ask

What does @ID do in JPA?

Simple Identifiers. The most straightforward way to define an identifier is by using the @Id annotation. Simple ids are mapped using @Id to a single property of one of these types: Java primitive and primitive wrapper types, String, Date, BigDecimal and BigInteger.

What is @ID annotation in JPA?

@Id annotation is the JPA is used for making specific variable primary key.

What is @ID annotation in Hibernate?

@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default. @Id annotation marks the identifier for this entity.

How do you make a string a primary key in Hibernate?

You just need to add an attribute to your entity, make sure that its type and name match the database column, annotate it with @Column and you're done. You can then use the primary key to load the entity, and Hibernate sets the primary key value automatically.


2 Answers

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; 
like image 76
Sotirios Delimanolis Avatar answered Oct 01 '22 11:10

Sotirios Delimanolis


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.

like image 43
Gyanendra Dwivedi Avatar answered Oct 01 '22 10:10

Gyanendra Dwivedi