These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 
Author Message
 Post subject: how to go from java to mappings to database?
PostPosted: Thu Jan 12, 2006 2:46 am 
Beginner
Beginner

Joined: Sun Jul 25, 2004 11:15 pm
Posts: 24
Hi
Is there a way to start with my java classes, and have the mappings and the database tables generated automatically?

I recall I've seen this being done somewhere before but i can't find it anymore. I looked in the docs, tutorials, searched the forums and looked in my Hibernate In Action book, and couldn't find it.

I appreciate it if someone can give me the answer broken down in two parts:
1- how automatically generate mappings (hbm.xml) from java files
2- how to create database tables from the mappings.


Thanks.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jan 12, 2006 4:18 am 
Regular
Regular

Joined: Wed Jun 29, 2005 11:14 pm
Posts: 119
Location: København
You can either use annotations or xdoclet in the java code.

Let's say you go for xdoclet.

Firslty, read up on the web on how to use xdoclet, but I will give you some pointers.

A POJO with xdoclet:
Code:
/**
* Hibernate xdoclet tags are included to generate the mapping files
* It is declared serializable to enable passing through to web layers. 
* It could be considered in the future to implement the Memento pattern
* to successfully serialze this object between applications running different
* versions of the code.  However, this is not required at this time.
*
* @hibernate.class
*       table="scientific_names"
*/
public class ScientificName implements Serializable {
   /**
    * To allow robust serialization
    */
   private static final long serialVersionUID = -7527155826957740342L;

   /**
    * The family we belong to
    */
   protected Family family;
   
   /**
    * The record id is a unique identifier
    */
   protected long recordId;

   /**
    * The name code
    */
   protected String nameCode;

   /**
    * The genus
    */
   protected String genus;

   /**
    * The species
    */
   protected String species;

   /**
    * The infraSpecies
    */
   protected String infraSpecies;

   /**
    * The infraSpeciesMarker
    */
   protected String infraSpeciesMarker;

   /**
    * The author
    */
   protected String author;

   /**
    * @return The unique record id
    * @hibernate.id
    *       generator-class="native"
    *       column="record_id"
    */
   public long getRecordId() {
      return recordId;
   }

   /**
    * @param recordId To set
    */
   public void setRecordId(long recordId) {
      this.recordId = recordId;
   }

   /**
    * @return Returns the family.
    * @hibernate.many-to-one
    *    column="family_id"
    *    not-null="true"
    */
   public Family getFamily() {
      return family;
   }

   /**
    * @param family The family to set.
    */
   public void setFamily(Family family) {
      this.family = family;
   }

   /**
    * @return Returns the author.
    * @hibernate.property
    *       column="author"
    */
   public String getAuthor() {
      return author;
   }

   /**
    * @param author The author to set.
    */
   public void setAuthor(String author) {
      this.author = author;
   }

   /**
    * @return Returns the genus.
    * @hibernate.property
    *       column="genus"
    */
   public String getGenus() {
      return genus;
   }

   /**
    * @param genus The genus to set.
    */
   public void setGenus(String genus) {
      this.genus = genus;
   }

   /**
    * @return Returns the infraSpecies.
    * @hibernate.property
    *       column="infraSpecies"
    */
   public String getInfraSpecies() {
      return infraSpecies;
   }

   /**
    * @param infraSpecies The infraSpecies to set.
    */
   public void setInfraSpecies(String infraSpecies) {
      this.infraSpecies = infraSpecies;
   }

   /**
    * @return Returns the infraSpeciesMarker.
    * @hibernate.property
    *       column="infraspecies_marker"
    */
   public String getInfraSpeciesMarker() {
      return infraSpeciesMarker;
   }

   /**
    * @param infraSpeciesMarker The infraSpeciesMarker to set.
    */
   public void setInfraSpeciesMarker(String infraSpeciesMarker) {
      this.infraSpeciesMarker = infraSpeciesMarker;
   }

   /**
    * @return Returns the nameCode.
    * @hibernate.property
    *       column="name_code"
    */
   public String getNameCode() {
      return nameCode;
   }

   /**
    * @param nameCode The nameCode to set.
    */
   public void setNameCode(String nameCode) {
      this.nameCode = nameCode;
   }

   /**
    * @return Returns the species.
    * @hibernate.property
    *       column="species"
    */
   public String getSpecies() {
      return species;
   }

   /**
    * @param species The species to set.
    */
   public void setSpecies(String species) {
      this.species = species;
   }

   /**
    * Considered equal if the target is the same type and has the same record id
    * @see java.lang.Object#equals(Object)
         * @todo: implement a proper equals and hashcode
    */
   public boolean equals(Object object) {
      if (!(object instanceof ScientificName)) {
         return false;
      }
      ScientificName target = (ScientificName) object;
      if (this.getRecordId() == target.getRecordId()) {
         return true;
      } else {
         return false;
      }
   }

   /**
    * A string representation of the dao for logging purposes
    * @see java.lang.Object#toString()
    */
   public String toString() {
      StringBuffer sb = new StringBuffer();
      sb.append(Long.toString(recordId))
         .append(" - ")
         .append(genus)
         .append(": ")
         .append(species)
         .append(": ")
         .append(author);
      return sb.toString();
   }
}


So, if you look at the code, you will see that there is @hibernate.XXX tags.
We now run a build script over this file to generate the mapping - something like this might help:



Code:
    <!-- The "hibernatedoclet" target generates Hibernate mapping files
         based on XDoclet marked-up Plain Old Java Object (POJO) -->
    <target name="hibernate.doclet" depends="prepare" description="Generate Hibernate mapping files">
       <taskdef name="hibernatedoclet" classname="xdoclet.modules.hibernate.HibernateDocletTask" classpathref="xdoclet.classpath"/>
        <hibernatedoclet destdir="${classes.dir}" excludedtags="@version,@author" addedtags="@xdoclet-generated at ${TODAY}"
            force="true">
            <fileset dir="${src.dir}" includes="**/model/**/*.java"/>
            <hibernate validatexml="true" version="3.0"/>
        </hibernatedoclet>
    </target>


And then, you may want to generate the hibernate config file itself like so:
Code:
   <!-- Based on the hibernate mapping template, generate the configuration -->
    <target name="generate.hibernate.config" depends="hibernate.doclet" description="Generate the database">
      <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="xdoclet.classpath" />
      <hibernatetool destdir="${classes.dir}">
         <configuration configurationfile="${conf.dir}/hibernate.dialect.xml">
            <fileset dir="${classes.dir}">
               <include name="**/*.hbm.xml" />
            </fileset>
         </configuration>
         <hbm2cfgXml/>
      </hibernatetool>
    </target>


And then you may wish a DB create script - personally I like to generate a SQL file and not run it against the DB. I've had typos before and dropped 16gig DB's by accident that then take several hours to import again. So this while just create the script - you'll see I even comment out the drop table stuff...:

Code:
   <!-- Based on the hibernate mappings, generate the database schema (DB must exist - it will be dropped though) -->
    <target name="generate.database.script" depends="prepare,generate.hibernate.config" description="Generate the database">
      <mkdir dir="${db.dir}"/>
       <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="xdoclet.classpath" />
      <hibernatetool destdir="${db.dir}">
         <classpath>
             <path location="${classes.dir}"/>
         </classpath>          
         <configuration configurationfile="${conf.dir}/hibernate.dialect.xml">
            <fileset dir="${classes.dir}">
               <include name="**/*.hbm.xml" />
            </fileset>
         </configuration>
         <hbm2ddl outputfilename="${project.name}-create.sql" export="false" console="true" create="true" />
      </hibernatetool>
      <!-- now fix the file -->
      <replaceregexp file="${db.dir}/${project.name}-create.sql"
                     match="^(alter table .* drop foreign key .*)"
                     replace="-- SKIP \1"
                     flags="i"
                     byline="true"/>         
      <replaceregexp file="${db.dir}/${project.name}-create.sql"
                     match="^(drop table if exists .*)"
                     replace="-- SKIP \1"
                     flags="i"
                     byline="true"/>         
    </target>


Just google Hibernate Tools and there is a page on this stuff somewhere on the hibernate site. You need xdoclet classpaths and things also, but I am assuming you know how to use ant.

Hope this gets you started quickly and easily - these are my working scripts and how I am working at the moment, so it does work.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Jan 19, 2006 8:33 pm 
Newbie

Joined: Tue Jan 10, 2006 9:22 am
Posts: 6
Lets say that I don't have xdoclet and that I used annotations, how is it go?

_________________
Best regards
Dirceu Semighini Filho


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jan 20, 2006 2:04 am 
Beginner
Beginner

Joined: Sun Jul 25, 2004 11:15 pm
Posts: 24
vonlinkerstain wrote:
Lets say that I don't have xdoclet and that I used annotations, how is it go?


Good question!
I was afraid to ask!

I hope someone can answer this.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jan 20, 2006 2:38 am 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 6:10 am
Posts: 8615
Location: Neuchatel, Switzerland (Danish)
read the tool docs and notice <annotationconfiguration...

_________________
Max
Don't forget to rate


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.