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.

Geração de Ids é problema do Banco e não do Java

Eu estava usando JPA e quando executei os testes unitários ocorreu a seguinte exceção:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save()
O Java quer que eu informe o Id. Por quê? Minha tabela usa sequences para gerar os Ids.

Depois de pesquisar, descobri que deve-se informar, por meio de uma GeneratedValue, como as chaves primárias serão geradas.

Como as minhas Ids são geradas automaticamente pelo banco de dados, eu tive que declarar a anotação dessa forma:
@GeneratedValue(strategy=GenerationType.IDENTITY)
O código da minha classe, que gerava a exceção acima era desse jeito:
@Entity
@Table(name = "authenticationlog", catalog = "mao", schema = "public")
public class AuthenticationLog implements Serializable {
@Id
@Column(name = "tansrvauthenticationlogid")
private Integer tansrvauthenticationlogid;
e agora está assim:
@Entity
@Table(name = "authenticationlog", catalog = "mao", schema = "public")
public class AuthenticationLog implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "tansrvauthenticationlogid")
private Integer tansrvauthenticationlogid;
Isso resolveu o meu problema. Espero que resolva o teu.

sexta-feira, julho 10, 2009

Some software related books I've read

Shelfari: Book reviews on your book blog