Automatic Generation of Database Tables
By pavel on Dhj 07, 2005
I've been silent for a looooong time. I wanted to write about use of Java Persistence API in plain Java Applications, about using Hibernate in NetBeans Java EE 5 and do some example that updates data. But Martin Adamek who works with me on Java EE 5 did all the hard work for me . Make sure you check his blog!
Today I would like to show a very nice new feature in GlassFish: automatic generation of database tables. In my last demo I started by creating database tables and then I created an entity class to represent the data and a JSF page to display them. Sounds a little complicated if you do not have any existing database to integrate with? You do not even care that much about the specific structure of tables in the database, just want the data stored somehow? This is exactly it.
Start like in the last demo: get a new daily build of NetBeans Java EE 5. You do not need to download Derby plugin from update center, it is now included in NetBeans build. For GlassFish you need a build number 30 from December 7th or newer (get a daily build until build 30 gets promoted).
Create a new web application project and create a persistence unit like we did last time, only this time you need to add two more properties:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"> <persistence-unit name="pu" transaction-type="JTA"> <jta-data-source>jdbc/__default</jta-data-source> <properties> <property name="ddl-generation" value="dropandcreate"/> <property name="toplink.platform.class.name" value="oracle.toplink.essentials.platform.database.DerbyPlatform"/> </properties> </persistence-unit> </persistence>
The ddl-generation property tells the application server to generate DDL and create the tables during deployment. There are three accepted values: "createtables", "dropandcreate", "none". The second property specifies the database dialect - for example the database data types used for int, String, etc. (Derby uses a different dialect then for example Oracle).
Start the database and connect to jdbc:derby://localhost:1527/sun-appserv-samples;create=true - this creates the database for the default data source registered in GlassFish. You will also be able to view the tables later - so that you believe me that they were generated.
Now you just create the entity class and the JSF page in the same way. When you deploy the application the table is created and the application works with it. Refresh the tables under the "Databases" node in runtime tab. Voila, you see the new table!
Note that GlassFish also generated a table named SEQUENCE. It is used by the generator of primary keys.