Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Support for schema migrations with JPA?

I've been briefly looking at JPA recently, and I was wondering what the deal is with database schema migrations and staying lined up with the classes you've created.

Is there support in JPA for this stuff? Utilities? Best Practises?

Cheers!

like image 504
brabster Avatar asked Jan 12 '10 22:01

brabster


People also ask

What is meant by schema migration?

In software engineering, a schema migration (also database migration, database change management) refers to the management of version-controlled, incremental and reversible changes to relational database schemas.


2 Answers

I won't rely on JPA providers to update the database schema. Check Liquibase for one of the good approaches.

like image 134
lexicore Avatar answered Oct 17 '22 23:10

lexicore


The short answer is no.

If you change your beans, then you will have to migrate the existing schema by hand. So for Rails style database migrations you will have to look elsewhere.

You can however generate the initial ddl from your Java beans easily. The example below illustrates schema creation with EclipseLink version 2.0:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="JPATestPU" transaction-type="RESOURCE_LOCAL">
        <provider>
            org.eclipse.persistence.jpa.PersistenceProvider
        </provider>
        <class>org.randompage.MyEntity</class>
        <properties>
            <property name="javax.persistence.jdbc.user" value="johndoe"/>
            <property name="javax.persistence.jdbc.password" value="secret"/>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:~/.h2/testdb;FILE_LOCK=NO"/>
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
            <property name="eclipselink.logging.level" value="INFO"/>
        </properties>
    </persistence-unit>
</persistence>

The key element here is

 <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/> 

This tells EclipseLink to drop existing tables and generate new once from your JPA mapping. This procedure is highly vendor specific so for other JPA vendors (Hibernate, OpenJPA...) you will have to consult their specific documentation.

like image 30
Lars Tackmann Avatar answered Oct 17 '22 23:10

Lars Tackmann