tags:

views:

122

answers:

2

What's the correct sintax of a JPA insert statement? This might sound like an easy question but I haven't been able to find an answer.

I know how to do it from Java code but I'm looking for a way to insert objects into the database if the database was created.

Any ideas?

A: 

There is no INSERT statement in JPA. You have to insert new entities using an EntityManager. The only statements allowed in JPA are SELECT, UPDATE and DELETE.

frm
I've seen native SQL being used for this purpose, but how can this been written for all database providers? Hibernate has such a feature, you can include a file called "import.sql" in the runtime classpath of Hibernate. At the time of schema export it will execute the SQL statements contained in that file after the schema has been exported.I'm looking for some more generic approach to this as I am using Eclipselink.
javydreamercsw
A: 

Here is a good reference on persisting JPA objects using an EntityManager. As an example, this is how to insert objects using the persist method:

EntityManager em = getEntityManager();
em.getTransaction().begin();

Employee employee = new Employee();
employee.setFirstName("Bob");
Address address = new Address();
address.setCity("Ottawa");
employee.setAddress(address);

em.persist(employee);

em.getTransaction().commit();
Ben Hoffstein
As I mentioned I'm aware on how to do it from Java. I'm looking for a way to use standard inserts when the database is created besides hardcoding it in java.
javydreamercsw
Gotcha - sorry, misunderstood the question.
Ben Hoffstein
No problem. Thanks anyways!
javydreamercsw