JPA insert statement

If you want to insert data to the database outside java you need to use native SQL. Use SQL Standard to make sure most databases can execute the script. When the application runs, JPA will make the mapping of the new data and convert it into objects when needed.

How to make sure the script works in all databases? well thats the same problem any DBA has when making Store Procedures or native queries... thats why JPA exists, to avoid making it directly in SQL, but I know sometimes is needed that way.

I suggest you to make 3 main scripts. One for Oracle, one for SQL Server (there are some issues in the date datatypes from 2005 to 2008 versions so be careful) and one for MySQL. Start your script with standard SQL and when you test it in this databases you will find some fixes you will need to do for each DBMS.

One you got it you can make a file script (*.sql) file and run it with the DB manager. If it works run the server, put the app online and the data will be integrated just fine.


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();

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.

Tags:

Jpa