I have a mysql database that I want to add the functionality of adding a new table to the database. I could probably easily find the example of the JPQL for this but how would I then automatically generate the entity for this new table so that I could reference it in the rest of my JPA code for updating and deleting from the table I usually reference the entity not the actual table itself.
The Entities I have now I've used eclipe to generate from the tables I created. But after deployment we obviously won't have Eclipse to do this so we need it done automatically every time a table is created.
Creating and mapping new tables dynamically is not something that JPA supports. It would need creating new Java classes on the fly and dynamically update the mapping metadata. You can do everything you want with JDBC or native queries. But maybe you should explain why you need to create new tables on the fly.
There are a couple of ways to create the tables. The most common for production usage is that the DBA (or developer in that role) creates the database schema (tables etc) independently of the application.
This is typical, since the application then models the data in the database, and there's a common wisdom that says the database normally outlives the application.
It is possible to let the JPA provider automatically create the schema. There are even a couple of attributes on the JPA annotations that are specifically for this purpose (e.g. the nullable
attribute JoinColumn
).
Activating this happens with provider specific properties in persistence.xml. E.g. hibernate.hbm2ddl.auto
for Hibernate (as used in JBoss AS) and eclipselink.ddl-generation
for EclipseLink (as used in GlassFish).
See http://wiki.eclipse.org/EclipseLink/Examples/JPA/Migration/JBoss for some examples.
Inserting an entity in a table is a completely different thing. From your question is somehow get the feeling that you might not fully understand the difference between those two. It happens via e.g. EntityManager#persist
, but I'm not 100% sure if this is what you're asking.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With