Friday, January 18, 2008

2 things to remember when using JPA

Java persistence API offers a great Object Relational Mapping framework to develop java application. In combination with a wizzard that auto-generates the entity classes from your databse, it makes an easy, clean, and quick way to store your data in a database. Unfortunately, some or the errors you can get with JPA are not always easy to debug. So here are the two lessons I learned while spending hours trying to debug my code:

1)If you have a bidirectionnal relationthip (annotated with a @mapped_by), it is your responsability to make sure that the two fields that reference each-other contain what they should. I say it again, it is YOUR responsability. And if it doesn't, and you try to persist your object, you will probably get a violation constraint in you database, without JPA telling you that you messed up.

2)If your table has a field table_id, which value is auto-generated by your database, make sure to annotate the mapping java field with @Id and @GeneratedValue(strategy="IDENTITY"). If you don't, everything will work fine when you just persist your table, but things won't work when persisting the table in cascade.

No comments: