helloworld1234
helloworld1234

Reputation: 327

Add new column to MySQL through JPA

I would like to add a new column to MySQL table using JPA. How can I achieve it?

My concern is, even though the table can be updated, how can I update the entity so the column is usable for query by using JPA? or is there any other solution?

Upvotes: 0

Views: 2732

Answers (2)

coladict
coladict

Reputation: 5095

There are several ways of doing it, mostly through properties in persistence.xml. One standard way would be using javax.persistence.schema-generation.scripts.create-script-source, which may or may not be run every time you start the webapp, most likely leading to exceptions on start-up and possibly the destruction of your data.

In Hibernate, you can make it update your tables according to your entities using the hibernate.hbm2ddl.auto to update.

http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl

In EclipseLink there is the eclipselink.ddl-generation property. The create-or-extend-tables settings seems appropriate.

http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/p_ddl_generation.htm

However, generally speaking, using JPA to maintain your schema is less reliable than manually updating it with a pre-written script at the time of updating the production server's webapp.

Upvotes: 2

Neil Stockton
Neil Stockton

Reputation: 11531

JPA doesn't provide for "on-the-fly" schema updates (and certainly not for dynamic updates to entity classes).

Some providers will allow addition of columns when the EMF is created (DataNucleus JPA does, for example), when the entity class can be reloaded. That is all there is. Other than that, re-architect your application

Upvotes: 0

Related Questions