跳至主要内容

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.

评论

此博客中的热门博文

Create a restful application with AngularJS and Zend 2 framework

Create a restful application with AngularJS and Zend 2 framework This example application uses AngularJS/Bootstrap as frontend and Zend2 Framework as REST API producer. The backend code This backend code reuses the database scheme and codes of the official Zend Tutorial, and REST API support is also from the Zend community. Getting Started with Zend Framework 2 Getting Started with REST and Zend Framework 2 Zend2 provides a   AbstractRestfulController   for RESR API producing. class AlbumController extends AbstractRestfulController { public function getList() { $results = $this->getAlbumTable()->fetchAll(); $data = array(); foreach ($results as $result) { $data[] = $result; } return new JsonModel(array( 'data' => $data) ); } public function get($id) { $album = $this->getAlbumTable()->getAlbum($id); return new JsonModel(array("data" =>

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 the   Post   entity 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 convert

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 add   hibernate-envers   as 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   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa