开发者

Hibernate does not save my newly created objects

I have a pretty simple tables structure: table Products with product_id and name attributes. table Barcodes with product_id (foreign key to the开发者_C百科 Products table) and code attributes.

In my code I create new instance of a Product object:

Product product = new Product();

and I save the product:

session.save(product);

Later I create new instance of a Barcode object:

Barcode barcode = new Barcode();

and associate the product with the barcode:

barcode.setProduct(product);

and try to save the barcode:

session.save(barcode);

and I'm getting:

Exception in thread "main" org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:

Any ideas?


At least a couple of ideas:

  • You've mapped an @Id field without a generation strategy, and you're not setting the id yourself.
  • If your Barcodes table really only has the two columns, then you're probably setting the product_id as the @Id column, and if you were to create two Barcode objects for the same Product, this would happen.

For more ideas, give more details.


Like JB said your mapping files (and the actual code) would really help. For now you can try adding:

session.flush()

After:

session.save(product)

I'm guessing that hibernate is trying to "optimize" this transaction and saves the same product again when you're saving the barcode.

But that's only one possibility. Do you have any loops in your code?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜