Table of Contents
This chapter contains a large selection of examples. The complete examples including mapping, classes and a test class showing how to insert, update, delete and query the mapped objects can be found in the example Java project mapping-examples-xml for XML mappings and mapping-examples-annotation for annotation mapping.
There are two approaches to mapping: XML and Annotation. The latter is standardised as Java Persistence and Hibernate supports it since version 3.x. Annotation mapping requires Java 1.5 alias 5 and is the preferred mapping approach by many people.
Annotation mappings are defined directly in the class.
This book contains many but not all existing mappings. I recommend two sources to look up further mappings. The hibernate reference and the JUnit test cases of Hibernate. The source code provided with the Hibernate download has a test folder containing many complicated and inspiring variations.
Class mapped with annotations.
import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name="computer") @SequenceGenerator(name="computer_seq", sequenceName="computer_id_seq") public class Computer implements Serializable{ private static final long serialVersionUID = 3322530785985822682L; @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="computer_seq") private Integer id; private String name; public Computer() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "Computer: " + getId() + " Name: " + getName(); } }
Annotations start always with an @ character. @Entity defines that this class is a mapped class. @Table specifies that the entity is mapped to the table computer @SequenceGenerator specifies the Hibernate name and the database name of a sequence, which can be used to generate unique values. @Id defines the primary key of the class and @GeneratedValue specifies that the id is generated by the sequence, we defined at the beginning of the class.
Careful chosen default behaviour. Annotation mapping has careful chosen default behaviour. Hopefully in most cases you do not have to write anything to get the wanted behaviour.
Advantages of annotation mapping over XML mapping files
Disadvantages
Opinion: I think that annotation mapping is clearer, faster and represents the future approach to mapping. You might consider to use it as well. In the next chapters, I will explain both approaches to you.