quarta-feira, julho 22, 2009

Id creation is a database job. It is not not concerned to Java

I was using JPA and when I've run unit tests I got the following exception:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()
Java requires me to inform him which Id it must use. Why? My table uses sequences in order to generate Ids.

So after some research I found out that JPA's users must let java aware the way primary keys will be generated and we use an annotation named GeneratedValue to do this.

As my Ids are automatically generated by database, we must declare the following annotation:
@GeneratedValue(strategy=GenerationType.IDENTITY)
This was the code that was generating the exception:
@Entity
@Table(name = "authenticationlog", catalog = "mao", schema = "public")
public class AuthenticationLog implements Serializable {
@Id
@Column(name = "tansrvauthenticationlogid")
private Integer tansrvauthenticationlogid;
and now it is this way:
@Entity
@Table(name = "authenticationlog", catalog = "mao", schema = "public")
public class AuthenticationLog implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "tansrvauthenticationlogid")
private Integer tansrvauthenticationlogid;
This solved my problem. I hope it will solve yours too.

Nenhum comentário: