Reputation: 101
I have a relationship: Client has an Account. So the following implementation is
Account.class:
@Column(name = "client_id")
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign",
parameters = { @Parameter(name = "property", value = "clientDTO") })
private int client_id;
Client.class:
@OneToOne(cascade = CascadeType.ALL)
private AccountDTO accountDTO;
I init a Client, Account, and set account to the client, but when I try save it to db, I get an exception:
java.sql.BatchUpdateException: Batch entry 0 insert into public.accounts (balance, client_id, comment, credit_limit, id) values (1000.0, 0, comment, 0.0, 8) was aborted. Call getNextException to see the cause.
As you see, my app tried to insert the account with client_id = 0;
How can I resolve it?
Upvotes: 0
Views: 995
Reputation: 101
I have been solved it. The main problem is the bi-directional relationship. So I had to set Account to Client, and Client to Acount. Thanks for all!
Upvotes: 0
Reputation: 2054
Take a look at my answer to this related question. You don't need the extra client_id
column in your account
table if the value should be the same as the id of the account
table. You can make the id of the account table the primary key and a foreign key referencing the client
table.
And this is what your usage of @GenericGenerator
with strategy = 'foreign'
suggests, but you are missing the @PrimaryJoinColumn
annotation. On top of this your @OneToOne
property is on the wrong side. According to your exception the Account entity should reference a Client and not vice-versa.
HTH
Upvotes: 0
Reputation: 133492
Use a java.lang.Integer instead of a primitive int-- that way Hibernate can tell that it hasn't been set yet, and needs to be generated (or passed as null). Or you can specify unsaved-value=0 (not sure how to do that from annotations though)
Upvotes: 1