Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

different object with the same identifier

 
sam liya
Ranch Hand
Posts: 1243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
below is my main class



above code working fine.but if i uncomment the below part it gives an exception.



the exception is below

 
Hauke Ingmar Schmidt
Rancher
Posts: 436
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Without seeing the User class we can't tell something definitive. But the exception is quite unambiguous. I bet there is something like

in it instead of a more helpful
 
sam liya
Ranch Hand
Posts: 1243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
below is user class

 
Hauke Ingmar Schmidt
Rancher
Posts: 436
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, it is int then. But the same problem.
 
sam liya
Ranch Hand
Posts: 1243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why it gives that exce.ption when use int?
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the default value for an int is 0 and you must have persisted a user with this identifier already.

Change int to Integer or Long where the default value is null. That way, Hibernate will populate the id for you when you persist the new user.

When using Hibernate, a new entity should not have the @Id field populated. It should be present when you wish to update an entity already persisted.
 
sam liya
Ranch Hand
Posts: 1243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I change user class as below



Then it gives me below exception


 
Hauke Ingmar Schmidt
Rancher
Posts: 436
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now that you don't have a wrong id (i.e. always the same, 0) but instead simply no id you need to care for a correct id. This is not done automatically; if you don't further annotate the id field you can do this yourself, as in set the value manually. In most cases (i.e. all where you don't have a natural or an external id) it is a better idea to let the database generate it. You can annotate the field with @GeneratedValue to activate this.
 
James Boswell
Bartender
Posts: 1051
5
Chrome Eclipse IDE Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On a side note, best to make those instance variables private

 
sam liya
Ranch Hand
Posts: 1243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Boswell
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic