跳至主要内容

JPA 2.1 Schema generation properties


JPA 2.1 Schema generation properties

If you have some experience of Hibernate before, you must have used Hibernatehibernate.hbm2ddl.auto property to maintain the database schema for your project and used import.sql to initialize test data into the database.
Luckily this feature is standardized in JPA 2.1
JPA 2.1 added a series of properties for database schema maintenance and generation.

Maintain database schema

Let's create a simple Entity as example.
@Entity
@Table(name="POSTS")
public class Post implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ID")
    private Long id;
    
    @Column(name="TITLE")
    private String title;
    
    @Column(name="BODY")
    private String body;
    
    @Temporal(javax.persistence.TemporalType.DATE)
    @Column(name="CREATED")
    private Date created;
}
A simple Post class, includes three properties, title, body, created, and additional id.
An example of persitence.xml.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="postpu" transaction-type="JTA">
        <properties>
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
            <property name="javax.persistence.schema-generation.create-source" value="script"/>
            <property name="javax.persistence.schema-generation.drop-source" value="script"/>
            <property name="javax.persistence.schema-generation.drop-script-source" value="META-INF/drop-script.sql"/>
            <property name="javax.persistence.schema-generation.create-script-source" value="META-INF/create-script.sql"/>
            <property name="javax.persistence.sql-load-script-source" value="META-INF/load-script.sql"/>
            <property name="eclipselink.logging.level" value="FINE"/> 
        </properties>
    </persistence-unit>
</persistence>
javax.persistence.schema-generation.database.action defines the strategy will perform on database artifacts(tables, constraints etc). The value options are none, create, drop, create-and-drop.
javax.persistence.schema-generation.create-source specifies how to create these artifacts, the value could be script, metadata, script-then-metadata, metadata-then-script, which indicates the artifacts will be created from scripts or entity metadata, or scripts firstly then metadata, or metadata firstly then scripts. If script is specified, you can define anotherjavax.persistence.schema-generation.create-script-source property to locate the script.
javax.persistence.schema-generation.drop-source and javax.persistence.schema-generation.drop-script-source are easy to understand, which define the strategy to drop the artifacts.
javax.persistence.sql-load-script-source will initialize some test data into the database.
The following are samples of the three scripts.
The content of create-script.sql.
CREATE TABLE POSTS("ID" INTEGER NOT NULL PRIMARY KEY, "TITLE" VARCHAR(255), "BODY" VARCHAR(2000), "CREATED" DATE)
The content of drop-script.sql.
DROP TABLE POSTS
The content of load-script.sql.
INSERT INTO POSTS("ID", "TITLE", "BODY", "CREATED") VALUES (1, 'First Post', 'Body of first post', '2013-11-27')
INSERT INTO POSTS("ID", "TITLE", "BODY", "CREATED") VALUES (2, 'Second Post', 'Body of second post', '2013-11-27')
INSERT INTO POSTS("ID", "TITLE", "BODY", "CREATED") VALUES (3, 'Third Post', 'Body of third post', '2013-11-27')
When you run this project on Glassfish 4, you will see the sample data is loaded successfully at runtime.
NOTE, you could notice we have not defined a DataSource in the persistence.xml. Java EE 7 specs added a series of default resources, including Jdbc, JMS etc. If there is no Jdbc DataSource specified, the application will search the default Jdbc DataSource via JNDI name java:/comp/DefaultDataSource, it should be provided in any Java EE certificated application servers.
In the above example we use scripts to manage the tables. If you prefer models(aka metadata) to manage the database schema, there is an example.
<persistence version="2.1" 
             xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="postpu" transaction-type="JTA">
        <properties>
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
            <property name="javax.persistence.schema-generation.create-source" value="metadata"/>
            <property name="javax.persistence.schema-generation.drop-source" value="metadata"/>
            <property name="javax.persistence.sql-load-script-source" value="META-INF/load-script.sql"/>
            <property name="eclipselink.logging.level" value="FINE"/> 
        </properties>
    </persistence-unit>
</persistence>
This example is similar with Hibernate drop-create strategy.

Generate database schema

JPA 2.1 provides capability to generate the existing database schema into external resource.
There is an example of the usage from EclipseLink project wiki.
Map properties = new HashMap();
properties.put("javax.persistence.database-product-name", "Oracle");
properties.put("javax.persistence.database-major-version", 12);
properties.put("javax.persistence.database-minor-version", 1);
properties.put("javax.persistence.schema-generation.scripts.action", "drop-and-create");
properties.put("javax.persistence.schema-generation.scripts.drop-target", "jpa21-generate-schema-no-connection-drop.jdbc");
properties.put("javax.persistence.schema-generation.scripts.create-target", "jpa21-generate-schema-no-connection-create.jdbc");
    
Persistence.generateSchema("default", properties);
Try it yourself

Summary

This feature is good, but it lack an equivalent action to Hibernate update strategy. And the naming of these properties is very bad, I have to research the JPA document to differentiate their usage.
The sample codes are hosted on my github.com account, check out and play it yourself.
发表评论

此博客中的热门博文

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse thePostentity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute converter In this example…

Spring Data Mongo: bridge MongoDB and Spring

Spring Data Mongo: bridge MongoDB and SpringMongoDBis one of the most popular NoSQL products, Spring Data Mongo(Maven archetype id is spring-data-mongodb) tries to provides a simple approach to access MongoDB. Configuration Add the following code fragments in your Spring configuration. <!-- Mongo config --> <mongo:db-factory id="mongoDbFactory" host="localhost" port="27017" dbname="conference-db" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> </bean> <mongo:repositories base-package="com.hantsylabs.example.spring.mongo" /> Firstly, declare aDbFactorywhich is responsible for connecting to the MongoDB server. Then, register theMongoTemplateobject which envelop the data operations on MongoDB. Lastly addmongo:repositorieswith an essentialbase-packageattribute, Spring will discovery your d…

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to addhibernate-enversas project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple@Auditedannotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If@Auditedannotation is placed on a property, this property can be tracked.