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
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.
@Id annotation is the JPA is used for making specific variable primary key.
@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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With