Hibernate

Collection Mapping

Reference

Set<String>

Star.java

private Set<String> planets = new HashSet<String>();

Star.hbm.xml

<set name="planets" table="star_planet">
	<key column="star_id" />
	<element type="text"/>
</set>

SortedSet<String>

Star.java

private SortedSet<String> planets = new TreeSet<String>();

Star.hbm.xml

<set name="planets" table="star_planet" sort="natural">
	<key column="star_id" />
	<element type="text"/>
</set>

List<String>

Star.java

private List<String> planets = new LinkedList<String>();

Star.hbm.xml

<list name="planets" table="star_planet">
	<key column="star_id" />
	<list-index column="index" />
	<element type="text"/>
</list>

Map<String, String>

Star.java

private Map<String, String> planets = new HashMap<String, String>();

Star.hbm.xml

<map name="planets" table="star_planet">
	<key column="star_id" />
	<map-key type="text" column="planet_name" />
	<element type="text" column="planet_description"/>
</map>

List<Planet>

Star.java

private List<Planet> planets = new LinkedList<Planet>();

Star.hbm.xml

<list name="planets" table="star_planet">
  <key column="star_id" />
  <list-index column="index" />
  <many-to-many column="planet_id" class="Planet"/>
</list>

Writing Hibernate Mapping Files

Sort model classes

In Eclipse:

  • For each model class: Source -> Sort Members

Write Hibernate files

For each model class (Toto.java):

  • create the Hibernate file (Toto.hbm.xml) in the same folder as the model class

Note: when using inheritance, subclasses' Hibernate mapping can be done in their superclass' mapping file.

Declare each Hibernate file in hibernate.cfg.xml

For each model class:

  • write simple attributes (String, Integer, Short, Date...) mappings in Hibernate file

For each model class:

  • write collections and relationships mappings in Hibernate file
  • Don't forget inter-package relationships.
  • Bidirectional relationships: make sure one side has inverse=“true”

Reserved SQL keywords

Enclose the table or column name in backticks

<class name="User" table="`user`">
</class>

Reference: http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#mapping-quotedidentifiers

Then for command line SQL queries (PostGreSQL):

SELECT * FROM "user";
-- or
SELECT * FROM public.user;

Conventions

  • Use ImprovedNamingStrategy: field and class names like “aPerfectAddress” will be transformed to “a_perfect_adress” when performing SQL queries. When creating the Hibernate's configuration (usually in HibernateUtil.java):
      Configuration cfg = new Configuration();
      cfg.setNamingStrategy(ImprovedNamingStrategy.INSTANCE);
      cfg.configure();

To generate the SQL schema accordingly with ant:

  <target name="schemaexport">
    <hibernatetool destdir="./">
     <configuration namingstrategy="org.hibernate.cfg.ImprovedNamingStrategy" configurationfile="${build.dir}/hibernate.cfg.xml"/>
      <hbm2ddl
          export="false"
          create="true"
          drop="false"
          delimiter=";"
          outputfilename="schema-export.sql"/>
    </hibernatetool>
  </target>
  • for String fields, specify type=“text” (to avoid SQL varchar issues)

Example:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping package="ca.sfm.entity.characters">
 
  <class name="Toto">
    <id name="id">
      <generator class="native"/>
    </id>
    <version name="version"/>
    <property name="aPerfectAddress" type="text"/>
    <property name="mySecretAge" />
  </class>
 
</hibernate-mapping>

Misc

Notion of automatic dirty checking. Flushing is the process of synchronizing the memory state with the database. Updating makes a detached object persistent again (binds it to a new unit of work): so the actual database data will be updated.

Bi-directional links: it's important to set the link on both sides. All bi-directional associations need one side as inverse.

Sets: a defensive programming method is to set the getter/setter as protected, and add addToAnimals and removeFromAnimals methods.

Use one Hibernate session per request.

setFlushMode(FlushMode.MANUAL) is for read-only transactions. Test if it actually speeds things up.Ref

crit.createAlias(“parent”, “parent”, CriteriaSpecification.LEFT_JOIN); Create an alias without excluding those with parent==null

Feedback

7
lol
Jan 2, 2011
#1
Can any one provide me how do I map
Map<CustomeObject1, List<CustomeObject2>> in .hbm file?

Please let me know if any one have solution.
Navnath
Jan 17, 2011
#2
Useful. One point that I would have liked to find is how to do the hibernate mapping of Sets, Lists and Sorted Sets with annotations. But thanks for sharing :-)
Akku
Jun 27, 2011
#3
nice tutorial i l loved it ...
Ju
Jul 27, 2011
#4
thank you
Colin
Nov 10, 2011
#5
thank you:)

Nov 26, 2011
#6
its ok muñeco
maco
Dec 28, 2011
#7
Thanks for the List<Planet> example! Exactly what I needed.

Nov 21, 2012
#8
hi
vivek
Jul 19, 2013
#9
Thank you
chari
Mar 3, 2014
#10
You are the best!
Thanks You so much!
Best regards, from Argentina.
elmerdeve
Dec 23, 2015
#11