Standalone Persistence example with bug?

Mike Rocks

Greenhorn

Posts: 3

posted 8 years ago

Hello Ranchers,

I am going through the examples of O'Reillys EJB 3.0 Book. There is an example (ex05_2) that has a J2SE-Client which make the persistence directly/self over JDBC in the hypersonic database. The client instantiates a cabin-class entity and persists it with an EntityManager like following:

When I test the code I get an error: "detached entity passed to persist". When I change the line "manager.persist(cabin_1)" to "manager.merge(cabin_1)" then the example works. The cabin_1 entity has a field marked as ID and the actual ID is definitely not yet used in the database.

There is no problem in the code- it looks like that cabin_1 entity hold's your primary key.

When you persist it by using the code- --------------------------- manager.persist(cabin_1); -------------------------------- first time when you run, it will work. Second time it will give you error. it is actually giving the unique constraint violation error. Please look at your server logs. But at the console, it will give the error as 'detached entity persist....'

but when you are doing the code

--------------------------- manager.merge(cabin_1);

-----------------------------

it is actually updatinng the same record. that's why it didn't gives error.

thanks for your replies. I found the error with your hints at the ID. I've made a fault AND Jboss has a curious behavier.

The ID was auto-generated from my database (MS SQL Server)

and therefore I couldn't set the ID myself. I overlooked this because I copied the entity from another example. :roll: Now that I don't set the ID the code works fine with persist().

BUT why does the Jboss server adds a new Cabin with the next new ID with merge(), when I set the ID myself to a different higher number and have auto-generated IDs? I think that there should come an error message like "cannot merge the entity, because no such ID in database"...