Annotations<br />2008 Intertech Oxygen Blast<br />
Before we begin…<br />Good afternoon and welcome!  My name is Jim White.<br />Have you used WebEx before???<br />A quick i...
Who is this guy?<br />Jim White – jwhite@intertech.com<br />Author J2ME, Java in Small Things – 2002, Manning<br />Interna...
Objectives<br />The objectives for today’s talk are to learn about Hibernate Annotations.<br />The pros/cons of using anno...
Metadata<br />JDK 5.0 introduced annotations to the Java programming language.<br />Annotations put meta information or me...
Metadata Cont.<br />Annotations are a form of attribute-oriented programming.<br />Attribute-oriented programming is a pro...
Metadata Cont.<br />In general, annotations allow metadata, like that in Hibernate mapping files, to be put next to the in...
Metadata Cont.<br />Hibernate Annotations were introduced with Hibernate Core 3.<br />A Java 5 environment is required in ...
Annotations Pros/Cons<br />Before exploring Annotations in Hibernate, a few of the pros/cons should be discussed.<br />Jav...
Annotations Pros/Cons Cont.<br />Annotations can replace XML deployment descriptors and configurations.<br />Annotations a...
Annotations Pros/Cons Cont.<br />Some configuration/deployment information can now be shared across programming environmen...
Annotations Pros/Cons Cont.<br />Annotations are part of the source code.<br />This can be a pro in the sense that the ann...
Hibernate Annotation Libraries<br />In order to use Hibernate annotations, additional Hibernate JAR files are required.<br...
Configuring Hibernate Annotations<br />When using Hibernate annotations, you use Hibernate annotations configuration when ...
Configuring Hibernate Annotations Cont.<br />The intent of using annotations is to remove (or at least greatly reduce) the...
Configuring Hibernate Annotations Cont.<br />While you can use both annotations and mapping files, you should not use both...
Configuring Hibernate Annotations Cont.<br />If not specified in the hibernate.cfg.xml, the annotated classes/packages can...
Configuring Hibernate Annotations Cont.<br />No other configuration changes are required to use annotations.  Hibernate pr...
EJB3/JPA Annotations<br />The title of this section might have confused you.  EJBs?  JPA?  Where did that come from?<br />...
Exploring Annotations<br />Perhaps the best way to explore the JPA and Hibernate annotations is by example.<br />
Exploring Annotations Cont.<br />An exhaustive look at all the annotations is not possible in this limited time.<br />This...
Entity Hibernate XML Mapping<br />&lt;hibernate-mapping package=&quot;com.intertech.domain&quot;&gt;<br />	&lt;class name=...
Entity Annotations<br />To define a POJO or JavaBean as a persistent entity, use the @Entity annotation.<br />@Table annot...
Property Annotations<br />By default, all non-static properties of an entity are mapped by default.  No annotation is requ...
Property Annotations Cont.<br />Attributes of updatable and insertable on the @Column annotation allow properties to be pr...
Identifier Annotations<br />The @Id annotation should be applied to the identifier property.<br />The @GeneratedValue anno...
Identifier Annotations Cont.<br />By default, the strategy defaults to AUTO.<br />When using a SEQUENCE or TABLE generator...
Access via Annotations<br />Field versus getter/setter (property) access is defined by where the annotation is placed rela...
Inheritance Annotations<br />Recall that Hibernate has three ways to map inherited classes to database tables.<br />A tabl...
Inheritance Annotations Cont.<br />The table per concrete mapping is called the table per class strategy in JPA.<br />
Inheritance Annotations Cont.<br />&lt;/hibernate-mapping&gt;<br />&lt;hibernate-mapping package=&quot;com.intertech.domai...
Inheritance Annotations Cont.<br />@Entity<br />@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)<br />public abstr...
Inheritance Annotations Cont.<br />The table per subclass mapping is called the joined strategy in JPA.<br />
Inheritance Annotations Cont.<br />&lt;hibernate-mapping package=&quot;com.intertech.domain&quot;&gt;<br />  &lt;class nam...
Inheritance Annotations Cont.<br />@Entity<br />@Table(name=&quot;Player&quot;)<br />@Inheritance(strategy = InheritanceTy...
Inheritance Annotations Cont.<br />The last inheritance mapping option is the table per hierarchy strategy.  In JPA, this ...
Inheritance Annotations Cont.<br />&lt;hibernate-mapping package=&quot;com.intertech.domain&quot;&gt;<br />  &lt;class nam...
Inheritance Annotations Cont.<br />@Entity<br />@Table(name=&quot;Player&quot;)<br />@Inheritance(strategy = InheritanceTy...
One-to-one Association Annotations<br />In the example domain model, Team has a one-to-one relationship to Stadium instanc...
One-to-one Association Annotations Cont.<br />Note the cascading style for transitive persistence can be specified on the ...
One-to-one Association Annotations Cont.<br />Again, associations in Java can be bidirectional.  Without any other annotat...
Many-to-one Association Annotation<br />BallPlayers have a many-to-one relationship to Team objects in the current busines...
Many-to-one Association Annotation Cont.<br />In this case, the join column does not have to be explicitly specified as th...
Many-to-one Association Annotation Cont.<br />To make this association bidirectional, Team must map a collection of BallPl...
Query Annotations<br />Queries can be mapped in the class files as well.<br />Annotated named queries in entity class file...
Query Annotations Cont.<br />Use the @NamedQuery annotation at the top of an annotated entity.<br />It must be defined out...
Query Annotations Cont.<br />Executing an annotated named query is no different than executing a named query defined in a ...
Hibernate Annotations<br />Hibernate provides a set of its own annotations.<br />The Hibernate annotations extend the EJB ...
Hibernate Annotations Cont.<br />On the @Entity annotation Hibernate annotations allow for the addition of many additional...
Hibernate Annotations Cont.<br />Direct field versus property access (using getters/setters) is determined by the position...
Hibernate Annotations Cont.<br />While Hibernate will infer the data type using reflection.  To override the default type,...
Hibernate Annotations Cont.<br />While EJB 3/JPA does provide for a fetch strategy, Hibernate provides many more fetch mod...
Hibernate Annotations Cont.<br />Hibernate also offers far more cascading styles than does JPA.  Use Hibernate’s @Cascade ...
Summary<br />JDK 5.0 introduced annotations to the Java programming language.<br />Annotations put meta information or met...
Thank you for coming!<br />I hoped you learned something today about<br />A Java 5 environment is required in order to tak...
Upcoming SlideShare
Loading in...5
×

Java Annotations

8,347

Published on

http://www.intertech.com/Courses/Course.aspx?CourseID=99098

This slide deck is from an Intertech (http://www.Intertech.com) Oxygen Blast presentation on Annotations.

Published in: Technology, News & Politics
3 Comments
35 Likes
Statistics
Notes
No Downloads
Views
Total Views
8,347
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
3
Likes
35
Embeds 0
No embeds

No notes for slide

Java Annotations

  1. 1. Annotations<br />2008 Intertech Oxygen Blast<br />
  2. 2. Before we begin…<br />Good afternoon and welcome! My name is Jim White.<br />Have you used WebEx before???<br />A quick introduction to our meeting framework may be in order.<br />As we continue the talk, please use the WebEx Q&A facility to submit questions.<br />Technical difficulties – please email <br />Doug Laing at DLAING@intertech.com<br />Dan McCabe at DMCCABE@intertech.com<br /> - or call<br />651-994-8558<br />
  3. 3. Who is this guy?<br />Jim White – jwhite@intertech.com<br />Author J2ME, Java in Small Things – 2002, Manning<br />International Speaker<br />Including JavaOne<br />Contributor to many journals including:<br />JDJ<br />DevX.com<br />JavaPro<br />Consultant, engineer and architect with several companies<br />Most recently - Senior Technical Architect at Target Corp.<br />
  4. 4. Objectives<br />The objectives for today’s talk are to learn about Hibernate Annotations.<br />The pros/cons of using annotations<br />How to setup and configure Hibernate Annotations<br />How to apply Hibernate Annotations in your code to replace (or augment) Hibernate XML Mapping files<br />To understand the relationship of Hibernate Annotations to the Java Persistence API (JPA)<br />An understanding of Hibernate (API, config, mapping) is expected.<br />This material will be available to you on-line at: www.intertech.com<br />Any questions before we begin?<br />
  5. 5. Metadata<br />JDK 5.0 introduced annotations to the Java programming language.<br />Annotations put meta information or metadata into the Java code.<br />This metadata does not directly affect the programs meaning or semantics.<br />Instead, metadata affects the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program.<br />Annotations can be read from source files, class files, or reflectively at run time.<br />
  6. 6. Metadata Cont.<br />Annotations are a form of attribute-oriented programming.<br />Attribute-oriented programming is a program-level marking or “annotating” technique.<br />Javadocs include forms of attribute-oriented programming.<br />For example, the @deprecated Javadoc tag is metadata that indicates that the method should no longer be used.<br />Other programming environments such as C# have had them since the language was formed.<br />Java has had precursors to annotation for some time.<br />XDoclet was a popular means to annotate Java source code with meta-information in order to automatically create deployment descriptors, etc.<br />
  7. 7. Metadata Cont.<br />In general, annotations allow metadata, like that in Hibernate mapping files, to be put next to the information it describes.<br />That is in the class files next to the code it describes.<br />This is opposed to having this information in some separate file (the .hbm.xml file).<br />The reason for annotation is that when you update the class, you probably also want to update the information that describes the class.<br />The Hibernate Annotations package, used on top of the Hibernate Core, allows you to use metadata to replace or augment the XML mapping file.<br />
  8. 8. Metadata Cont.<br />Hibernate Annotations were introduced with Hibernate Core 3.<br />A Java 5 environment is required in order to take advantage of Hibernate Annotations.<br />Java Persistence Architecture API (JPA) is a Java specification for accessing, persisting and managing data between Java objects and the relational database.<br />JPA was defined as part of the EJB 3.0 specification as a replacement to the EJB 2 Container Managed Entity Beans.<br />In the Java community, JPA now sets the “standard industry approach” for object-relational mapping.<br />It is the JPA specification that defines object/relational mapping metadata syntax and semantics for ORM annotations.<br />Hibernate is considered an implementation of JPA. As such it offers EJB 3/JPA annotations.<br />
  9. 9. Annotations Pros/Cons<br />Before exploring Annotations in Hibernate, a few of the pros/cons should be discussed.<br />Java, and specifically Java EE, is embracing annotations aggressively.<br />They are, or soon will be, everywhere in your applications.<br />The EJB 3.0 and Java Persistence standards have fully embraced annotations.<br />Expert groups that are pushing the migration to annotations advise of certain limitations and considerations before adopting annotations.<br />The often sighted “pro” of annotation is that they are attached to the program artifacts they describe.<br />This gives the metadata information relevance that is not always there (or clear) when viewed in an XML file.<br />However, when searching an application for all the applicable and like program characteristics, an XML document makes the search concise.<br />
  10. 10. Annotations Pros/Cons Cont.<br />Annotations can replace XML deployment descriptors and configurations.<br />Annotations are typically much simpler to code than XML.<br />XML is not always the easiest of documents to read or maintain and it is often very verbose.<br />However, some configuration data changes with each deployment.<br />Consider what changes as you move your application from dev to test to stage to production platforms.<br />Annotations, as part of the Java code, can create significant issues when the configuration changes per platform.<br />Dev<br />Test<br />Stage<br />Prod<br />
  11. 11. Annotations Pros/Cons Cont.<br />Some configuration/deployment information can now be shared across programming environments.<br />Take for example Hibernate. nHibernate is now a framework for the .NET environment.<br />In time, could the XML configuration files of many frameworks like Hibernate be used cross-platform?<br />Annotations, as part of the actual source code, will not support and promote any cross-platform sharing.<br />
  12. 12. Annotations Pros/Cons Cont.<br />Annotations are part of the source code.<br />This can be a pro in the sense that the annotations are compiled right into the class files.<br />Since the annotations are with the code, an incorrect or stale XML file cannot be accidentally used to configure the application.<br />On the other hand, annotations can only be read at runtime.<br />Therefore, they cannot be added as additional XML can be at runtime.<br />When only the bytecode is available, annotations may create difficulties.<br />In this case, an XML file allows for application changes without the source. <br />Annotations cannot be validated in the same way that XML can be validated.<br />…<br />@Entity<br />@Table(name = &quot;Player&quot;, schema = &quot;MLB&quot;)<br />public abstract class BallPlayer {<br />…<br />…<br />&lt;hibernate-mapping package=&quot;com.intertech.domain&quot;&gt;<br /> &lt;class name=&quot;BallPlayer&quot; table=&quot;Player&quot; abstract=&quot;true&quot;&gt;<br /> &lt;id name=&quot;id&quot;&gt;<br />…<br />
  13. 13. Hibernate Annotation Libraries<br />In order to use Hibernate annotations, additional Hibernate JAR files are required.<br />Download the Hibernate Annotations distribution from Hibernate Web site.<br />www.hibernate.org<br />Extract the JAR files listed in the table below. Make these JARs available to your runtime and applicable IDE environment. <br />
  14. 14. Configuring Hibernate Annotations<br />When using Hibernate annotations, you use Hibernate annotations configuration when establishing the session factory.<br />This is in contrast to using the Hibernate Configuration object to load all the configuration information.<br />The AnnotationConfiguration class is defined in org.hibernate.cfg and extends org.hibernate.cfg.Configuration.<br />Therefore the same Configuration API works with AnnotationConfiguration.<br />SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();<br />SessionFactory sessionFactory = new Configuration(). configure().buildSessionFactory();<br />
  15. 15. Configuring Hibernate Annotations Cont.<br />The intent of using annotations is to remove (or at least greatly reduce) the number and size of the Hibernate mapping files.<br />The emphasis should be to move Hibernate mapping information into classes via annotation. <br />However, Hibernate must be signaled as to which classes are domain classes and which classes to examine for annotations.<br />In the Hibernate configuration file (hibernate.cfg.xml), the &lt;mapping&gt; element is used to specify domain classes to check for annotations.<br />This can be done by class or by package (suggesting all the classes in the package may have annotations and should be checked).<br />Hibernate mapping files can still be specified and used in the Hibernate configuration file (hibernate.cfg.xml).<br />&lt;mapping class=&quot;com.intertech.domain.BallPlayer&quot; /&gt;<br />&lt;mapping package=&quot;com.intertech.business.model&quot;/&gt;<br />
  16. 16. Configuring Hibernate Annotations Cont.<br />While you can use both annotations and mapping files, you should not use both annotations and a Hibernate mapping file for the same entity.<br />To ease the migration process and allow mapping files and annotations to coexist, Hibernate will not complain when there are duplicate mappings.<br />Hibernate mapping files have precedent over annotations by default.<br />You can change the default in the Hibernate configuration file by setting the hibernate.mapping.precedence property.<br />It defaults to “hbm, class” but can be set to “class, hbm”.<br />Removing either hbm or class from the property option, removes that form of configuration.<br />Again, however, this override mechanism was implemented for ease in migration to annotations. Dual mappings should be avoided.<br />hibernate.connection.username=sa<br />hibernate.dialect=org.hibernate.dialect.HSQLDialect<br />hibernate.mapping.precedence=class, hbm<br />
  17. 17. Configuring Hibernate Annotations Cont.<br />If not specified in the hibernate.cfg.xml, the annotated classes/packages can also be specified programmatically on the Configuration object.<br />SessionFactory sessionFactory = new AnnotationConfiguration(). configure().addPackage(&quot;com.intertech.business.model&quot;). addAnnotatedClass(com.intertech.domain.BallPlayer.class). buildSessionFactory();<br />
  18. 18. Configuring Hibernate Annotations Cont.<br />No other configuration changes are required to use annotations. Hibernate properties and other configurations remain unchanged.<br />Annotations do not require any changes in the way the Hibernate API behaves or is used.<br />
  19. 19. EJB3/JPA Annotations<br />The title of this section might have confused you. EJBs? JPA? Where did that come from?<br />Remember, the EJB 3.0 specification (that includes JPA) defines the metadata syntax and semantics.<br />Hibernate, as a JPA implementation, uses this syntax.<br />So when learning “Hibernate Annotations” you must first learn EJB3/JPA annotations.<br />There are additional Hibernate specific annotations called Hibernate annotation extensions. These are covered later.<br />The fact that there is a Java specification for the metadata is good.<br />It ultimately provides more portability among ORM capabilities.<br />However, the fact that many features/mappings available in Hibernate require Hibernate specific annotations potentially degrades portability.<br />Having EBJ3/JPA annotations and Hibernate annotations can also confuse developers new to annotations.<br />
  20. 20. Exploring Annotations<br />Perhaps the best way to explore the JPA and Hibernate annotations is by example.<br />
  21. 21. Exploring Annotations Cont.<br />An exhaustive look at all the annotations is not possible in this limited time.<br />This example should provide an example of the more widely used mappings in Hibernate<br />Entity mapping<br />Many-to-one (BallPlayer to Team)<br />One-to-one (Team to Stadium)<br />And Inheritance mapping (BallPlayer, Batter, Pitcher)<br />
  22. 22. Entity Hibernate XML Mapping<br />&lt;hibernate-mapping package=&quot;com.intertech.domain&quot;&gt;<br /> &lt;class name=&quot;Team&quot;&gt;<br /> &lt;id name=&quot;id&quot;&gt;<br /> &lt;generator class=&quot;sequence&quot;&gt;<br /> &lt;param name=&quot;sequence&quot;&gt;common_seq&lt;/param&gt;<br /> &lt;/generator&gt;<br /> &lt;/id&gt;<br /> &lt;property name=&quot;nickname&quot; /&gt;<br /> &lt;property name=&quot;founded&quot; /&gt;<br /> &lt;property name=&quot;mascot&quot; /&gt;<br /> …<br /> &lt;/class&gt;<br />&lt;/hibernate-mapping&gt;<br />
  23. 23. Entity Annotations<br />To define a POJO or JavaBean as a persistent entity, use the @Entity annotation.<br />@Table annotation allows you to explicitly specify the table to which the entity is mapped.<br />If not provided, the table name defaults to the name of the class.<br />Schema and catalog optional attributes can be specified on the @Table annotation.<br />import javax.persistence.Entity;<br />@Entity<br />public class Team {<br /> private long id;<br /> private String nickname;<br /> …<br />}<br />import javax.persistence.Entity;<br />import javax.persistence.Table;<br />@Entity<br />@Table(name = &quot;Player&quot;, schema=&quot;MLB&quot;)<br />public abstract class BallPlayer {<br /> private long id;<br /> …<br />}<br />
  24. 24. Property Annotations<br />By default, all non-static properties of an entity are mapped by default. No annotation is required to map properties.<br />If you do not want a property mapped, use the @Transient annotation to exclude the property.<br />Explicitly, you can use @Basic to annotate a property for mapping. This allows attributes like fetching strategies to be applied.<br />Use the @Column annotation to specify the database column name when the name does not match the property name.<br />@Entity<br />@Table(name = &quot;Player&quot;, schema=&quot;MLB&quot;)<br />public abstract class BallPlayer {<br /> private long id;<br />@Basic<br /> private String name; //default mapping<br /> private String nickname;<br />@Column(name = &quot;date_of_birth&quot;)<br /> private Calendar dob;<br />@Transient<br /> private int userInterfaceHandle;<br /> …<br />}<br />
  25. 25. Property Annotations Cont.<br />Attributes of updatable and insertable on the @Column annotation allow properties to be protected from modification.<br />@Column(updatable=false, insertable=false)<br />
  26. 26. Identifier Annotations<br />The @Id annotation should be applied to the identifier property.<br />The @GeneratedValue annotation allows you specify the Hibernate generator when used.<br />The EJB3/JPA specification defines only four generators (it calls these generator strategies).<br />The Hibernate extension annotations allow Hibernate’s additional generators to be used.<br />
  27. 27. Identifier Annotations Cont.<br />By default, the strategy defaults to AUTO.<br />When using a SEQUENCE or TABLE generator, use the proper annotation to specify the identifier in the database.<br />The sequence generator annotation is shown below. Use @TableGenerator annotation for the Table strategy.<br />When the name of the identifier property and column do not align, the @Column can again be used to explicitly specify the id column.<br />@Entity<br />public class Team {<br />@Id<br /> @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = &quot;myGenerator&quot;)<br /> @SequenceGenerator(name = &quot;myGenerator&quot;, sequenceName = &quot;common_seq&quot;)<br /> private long id;<br /> …<br />}<br />
  28. 28. Access via Annotations<br />Field versus getter/setter (property) access is defined by where the annotation is placed relative to the code.<br />Furthermore, an annotated entity inherits the default form (field versus property access) based on the position of the mandatory @Id annotation.<br />So if @Id is has been declared on the field, not a getter method, all other properties are accessed by getter and setter too.<br />//field access (for identifier and all implicit property mapping)<br />@Id<br />@GeneratedValue(strategy=GenerationType.SEQUENCE, generator=&quot;common_seq&quot;)<br />private long id<br />//versus method access (for id and all implicit property mappings)<br />@Id<br />@GeneratedValue(strategy=GenerationType.SEQUENCE, generator=&quot;myGenerator&quot;)<br />@SequenceGenerator(name=&quot;myGenerator&quot;, sequenceName=&quot;common_seq&quot;)<br />public long getId() {<br /> return id;<br />}<br />
  29. 29. Inheritance Annotations<br />Recall that Hibernate has three ways to map inherited classes to database tables.<br />A table is mapped to each concrete class in an inheritance hierarchy. This is called the table per concrete class strategy.<br />A table is mapped to each class and subclass in an inheritance hierarchy. This is called the table per subclass strategy.<br />The entire class hierarchy is mapped to a single table. This is called the table per hierarchy strategy.<br />JPA annotations support the same three ways to map inherited classes, but uses different names for the strategies.<br />
  30. 30. Inheritance Annotations Cont.<br />The table per concrete mapping is called the table per class strategy in JPA.<br />
  31. 31. Inheritance Annotations Cont.<br />&lt;/hibernate-mapping&gt;<br />&lt;hibernate-mapping package=&quot;com.intertech.domain&quot;&gt;<br /> &lt;class name=&quot;Pitcher&quot; table=&quot;Pitcher&quot;&gt;<br /> &lt;id name=&quot;id&quot;&gt;<br /> &lt;generator class=&quot;sequence&quot;&gt;<br /> &lt;param name=&quot;sequence&quot;&gt;common_seq&lt;/param&gt;<br /> &lt;/generator&gt;<br /> &lt;/id&gt;<br /> &lt;property name=&quot;name&quot; /&gt;<br /> &lt;property name=&quot;dob&quot; column=&quot;date_of_birth&quot; /&gt;<br /> &lt;property name=&quot;birthCity&quot; column=&quot;city_of_birth&quot; /&gt;<br /> &lt;property name=&quot;uniformNumber&quot; column=&quot;uniform_number&quot; /&gt;<br /> &lt;property name=&quot;handed&quot; column=&quot;throws&quot;/&gt;<br /> &lt;property name=&quot;wins&quot;/&gt;<br /> &lt;property name=&quot;losses&quot;/&gt;<br /> &lt;property name=&quot;earnedRunAverage&quot; column=&quot;earned_run_average&quot;/&gt;<br /> …<br />&lt;/class&gt;<br />&lt;/hibernate-mapping&gt;<br />&lt;hibernate-mapping package=&quot;com.intertech.domain&quot;&gt;<br /> &lt;class name=&quot;Batter&quot; table=&quot;Batter&quot;&gt;<br /> &lt;id name=&quot;id&quot;&gt;<br /> &lt;generator class=&quot;sequence&quot;&gt;<br /> &lt;param name=&quot;sequence&quot;&gt;common_seq&lt;/param&gt;<br /> &lt;/generator&gt;<br /> &lt;/id&gt;<br /> &lt;property name=&quot;name&quot; /&gt;<br /> &lt;property name=&quot;dob&quot; column=&quot;date_of_birth&quot; /&gt;<br /> &lt;property name=&quot;birthCity&quot; column=&quot;city_of_birth&quot; /&gt;<br /> &lt;property name=&quot;uniformNumber&quot; column=&quot;uniform_number&quot; /&gt;<br /> &lt;property name=&quot;position&quot; column=&quot;pos&quot;/&gt;<br /> &lt;property name=&quot;bats&quot;/&gt;<br /> &lt;property name=&quot;atBats&quot; column=&quot;at_bats&quot;/&gt;<br /> &lt;property name=&quot;hits&quot;/&gt;<br /> &lt;property name=&quot;homeRuns&quot; column=&quot;home_runs&quot;/&gt;<br /> …<br />&lt;/class&gt;<br />&lt;/hibernate-mapping&gt;<br />
  32. 32. Inheritance Annotations Cont.<br />@Entity<br />@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)<br />public abstract class BallPlayer{<br /> ...<br />}<br />@Entity<br />@Table(name=&quot;Batter&quot;) //explicit but not required<br />public class Batter extends BallPlayer {<br /> ...<br />}<br />@Entity<br />@Table(name=&quot;Pitcher&quot;) //explicit but not required<br />public class Pitcher extends BallPlayer {<br /> ...<br />}<br />
  33. 33. Inheritance Annotations Cont.<br />The table per subclass mapping is called the joined strategy in JPA.<br />
  34. 34. Inheritance Annotations Cont.<br />&lt;hibernate-mapping package=&quot;com.intertech.domain&quot;&gt;<br /> &lt;class name=&quot;BallPlayer&quot; table=&quot;Player&quot;&gt;<br /> &lt;id name=&quot;id&quot;&gt;<br /> &lt;generator class=&quot;sequence&quot;&gt;<br /> &lt;param name=&quot;sequence&quot;&gt;common_seq&lt;/param&gt;<br /> &lt;/generator&gt;<br /> &lt;/id&gt;<br /> &lt;property name=&quot;name&quot; /&gt;<br /> &lt;property name=&quot;dob&quot; column=&quot;date_of_birth&quot; /&gt;<br /> &lt;property name=&quot;birthCity&quot; column=&quot;city_of_birth&quot; /&gt;<br /> &lt;property name=&quot;uniformNumber&quot; column=&quot;uniform_number&quot; /&gt;<br /> …<br /> &lt;joined-subclass name=&quot;Batter&quot;&gt;<br /> &lt;key column=&quot;id&quot; /&gt;<br /> &lt;property name=&quot;position&quot; column=&quot;pos&quot; /&gt;<br /> &lt;property name=&quot;bats&quot; /&gt;<br /> &lt;property name=&quot;atBats&quot; column=&quot;at_bats&quot; /&gt;<br /> &lt;property name=&quot;hits&quot; /&gt;<br /> &lt;property name=&quot;homeRuns&quot; column=&quot;home_runs&quot; /&gt;<br /> &lt;/joined-subclass&gt;<br /> &lt;joined-subclass name=&quot;Pitcher&quot;&gt;<br /> &lt;key column=&quot;id&quot; /&gt;<br /> &lt;property name=&quot;handed&quot; column=&quot;throws&quot; /&gt;<br /> &lt;property name=&quot;wins&quot; /&gt;<br /> &lt;property name=&quot;losses&quot; /&gt;<br /> &lt;property name=&quot;earnedRunAverage&quot; column=&quot;earned_run_average&quot; /&gt;<br /> &lt;/joined-subclass&gt;<br /> &lt;/class&gt;<br />&lt;/hibernate-mapping&gt;<br />
  35. 35. Inheritance Annotations Cont.<br />@Entity<br />@Table(name=&quot;Player&quot;)<br />@Inheritance(strategy = InheritanceType.JOINED)<br />public abstract class BallPlayer{<br /> ...<br />}<br />@Entity<br />public class Batter extends BallPlayer {<br /> ...<br />}<br />@Entity<br />public class Pitcher extends BallPlayer {<br /> ...<br />}<br />
  36. 36. Inheritance Annotations Cont.<br />The last inheritance mapping option is the table per hierarchy strategy. In JPA, this is called aptly the single table strategy.<br />
  37. 37. Inheritance Annotations Cont.<br />&lt;hibernate-mapping package=&quot;com.intertech.domain&quot;&gt;<br /> &lt;class name=&quot;BallPlayer&quot; table=&quot;Player&quot;&gt;<br /> &lt;id name=&quot;id&quot;&gt;<br /> &lt;generator class=&quot;sequence&quot;&gt;<br /> &lt;param name=&quot;sequence&quot;&gt;common_seq&lt;/param&gt;<br /> &lt;/generator&gt;<br /> &lt;/id&gt;<br /> &lt;discriminator column=&quot;player_type&quot;/&gt;<br /> &lt;property name=&quot;name&quot; /&gt;<br /> &lt;property name=&quot;dob&quot; column=&quot;date_of_birth&quot; /&gt;<br /> &lt;property name=&quot;birthCity&quot; column=&quot;city_of_birth&quot; /&gt;<br /> &lt;property name=&quot;uniformNumber&quot; column=&quot;uniform_number&quot; /&gt;<br /> ….<br /> &lt;subclass name=&quot;Batter&quot; discriminator-value=&quot;B&quot;&gt;<br /> &lt;property name=&quot;position&quot; column=&quot;pos&quot; /&gt;<br /> &lt;property name=&quot;bats&quot; /&gt;<br /> &lt;property name=&quot;atBats&quot; column=&quot;at_bats&quot; /&gt;<br /> &lt;property name=&quot;hits&quot; /&gt;<br /> &lt;property name=&quot;homeRuns&quot; column=&quot;home_runs&quot; /&gt;<br /> &lt;/subclass&gt;<br /> &lt;subclass name=&quot;Pitcher&quot; discriminator-value=&quot;P&quot;&gt;<br /> &lt;property name=&quot;handed&quot; column=&quot;throws&quot; /&gt;<br /> &lt;property name=&quot;wins&quot; /&gt;<br /> &lt;property name=&quot;losses&quot; /&gt;<br /> &lt;property name=&quot;earnedRunAverage&quot; column=&quot;earned_run_average&quot; /&gt;<br /> &lt;/subclass&gt;<br /> &lt;/class&gt;<br />&lt;/hibernate-mapping&gt;<br />
  38. 38. Inheritance Annotations Cont.<br />@Entity<br />@Table(name=&quot;Player&quot;)<br />@Inheritance(strategy = InheritanceType.SINGLE_TABLE)<br />@DiscriminatorColumn(name=&quot;player_type&quot;, discriminatorType=DiscriminatorType.STRING)<br />public abstract class BallPlayer{<br /> ...<br />}<br />@Entity<br />@DiscriminatorValue(&quot;B&quot;)<br />public class Batter extends BallPlayer {<br /> ...<br />}<br />@Entity<br />@DiscriminatorValue(&quot;P&quot;)<br />public class Pitcher extends BallPlayer {<br /> ...<br />}<br />
  39. 39. One-to-one Association Annotations<br />In the example domain model, Team has a one-to-one relationship to Stadium instances.<br />In the Stadium.hbm.xml mapping file, this was mapped in XML as shown below.<br />To map this entity to entity association with JPA annotations, on the Stadium entity, use the @OneToOne annotation.<br />&lt;many-to-one name=&quot;team&quot; class=&quot;Team&quot; column=&quot;team_id“ unique=&quot;true&quot; /&gt;<br />@OneToOne(cascade = CascadeType.ALL)<br />@JoinColumn(name = &quot;team_id&quot;)<br />private Team team;<br />
  40. 40. One-to-one Association Annotations Cont.<br />Note the cascading style for transitive persistence can be specified on the association annotation.<br />JPA’s cascading styles are similar but identical to Hibernate’s cascading styles. <br />The @JoinColumn specifies the foreign key column in the Team table used to join to the Stadium table.<br />If a join column is not provided, by default it is assumed that the foreign key column is the name of the property type + underscore (_) + “id”.<br />In this case, that would mean that Team would need a foreign key column of HOMEFIELD_ID.<br />
  41. 41. One-to-one Association Annotations Cont.<br />Again, associations in Java can be bidirectional. Without any other annotations in the Team class, the relationship is unidirectional.<br />To make the relationship bidirectional, add the @OneToOne annotation to Team.<br />The mappedBy attribute has the effect of the property-ref attribute in the &lt;one-to-one&gt; element in the Hibernate XML mapping (shown below).<br />The property-ref attribute specifies the property in the associated class (Stadium in this case) that is joined to the primary key of Team class.<br />@OneToOne(mappedBy = &quot;team&quot;)<br />private Stadium homeField;<br />&lt;one-to-one name=&quot;homeField&quot; class=&quot;Stadium&quot; property-ref=&quot;team“ cascade=&quot;all&quot; /&gt;<br />
  42. 42. Many-to-one Association Annotation<br />BallPlayers have a many-to-one relationship to Team objects in the current business domain model.<br />From the BallPlayer to Team perspective, the many-to-one association to a Team object was mapped with the XML below.<br />Using JPA annotations, this same relationship is accomplished with a @ManyToOne annotation in the BallPlayer class.<br />&lt;many-to-one name=&quot;team&quot; column=&quot;team_id&quot; <br /> class=&quot;com.intertech.domain.Team&quot; /&gt;<br />@ManyToOne()<br />@JoinColumn()<br />private Team team;<br />
  43. 43. Many-to-one Association Annotation Cont.<br />In this case, the join column does not have to be explicitly specified as the default “property name + _ + id” is the name of the join column.<br />As in the @JoinColumn annotation for the one-to-one mapping, this can be made explicit if the default does not work.<br />@JoinColumn(name=”owning_team_id”)<br />
  44. 44. Many-to-one Association Annotation Cont.<br />To make this association bidirectional, Team must map a collection of BallPlayers.<br />The XML mapping for a set of BallPlayers is shown below.<br />Here is the JPA annotation in the Team class to implement the same the association from Tam back to the BallPlayer.<br />The mappedBy parameter is equivalent to the inverse attribute in the XML mapping.<br />&lt;set name=&quot;players&quot; inverse=&quot;true&quot;&gt;<br /> &lt;key column=&quot;team_id&quot; /&gt;<br /> &lt;one-to-many class=&quot;com.intertech.domain.BallPlayer&quot; /&gt;<br />&lt;/set&gt;<br />@OneToMany(mappedBy=&quot;team&quot;)<br />private Set&lt;BallPlayer&gt; players = new HashSet&lt;BallPlayer&gt;();<br />
  45. 45. Query Annotations<br />Queries can be mapped in the class files as well.<br />Annotated named queries in entity class files are considered “global” to the session factory.<br />Therefore, a query defined in BallPlayer is available by its name in other classes too.<br />Therefore, the query name must be unique.<br />
  46. 46. Query Annotations Cont.<br />Use the @NamedQuery annotation at the top of an annotated entity.<br />It must be defined outside of the actual class definition.<br />Query hints such as timeout and fetch size can also be provided as parameters.<br />@NamedQuery(name=&quot;getHomeRunHitters&quot;,query=&quot;from Batter where homeRuns &gt; :homeruns&quot;)<br />@Entity<br />@Table(name=&quot;Player&quot;)<br />@Inheritance(strategy = InheritanceType.SINGLE_TABLE)<br />@DiscriminatorColumn(name=&quot;player_type&quot;, discriminatorType=DiscriminatorType.STRING)<br />public abstract class BallPlayer{<br />...<br />}<br />@NamedQuery(name = &quot;getHomeRunHitters&quot;, <br />query = &quot;from Batter where homeRuns &gt; :homeruns&quot;, <br />hints = {<br />@QueryHint(name = &quot;org.hibernate.comment&quot;, value = &quot;My Comment&quot;),<br />@QueryHint(name = &quot;org.hibernate.timeout&quot;, value = &quot;60&quot;) })<br />
  47. 47. Query Annotations Cont.<br />Executing an annotated named query is no different than executing a named query defined in a mapping file.<br />In a similar fashion, named native queries can also be annotated in class files.<br />Query query = session.getNamedQuery(&quot;getHomeRunHitters&quot;);<br />List list = query.setInteger(&quot;homeruns&quot;, 5).list();<br />@NamedNativeQuery(name = &quot;getHomeRunHittersAndTeam&quot;,<br />resultClass = Batter.class, <br />query = &quot;select * from Player p join Team t on p.team_id = t.id where p.player_type = &apos;B&apos; and p.home_runs &gt; :homeruns&quot;)<br />
  48. 48. Hibernate Annotations<br />Hibernate provides a set of its own annotations.<br />The Hibernate annotations extend the EJB 3/JPA annotations.<br />That is Hibernate annotations are built on top of the JPA Annotations.<br />The Hibernate annotations provide a means to implement features of Hibernate’s XML mapping capabilities via annotations.<br />Not all of Hibernate’s mapping features are supported in the EJB 3/JPA specification.<br />Of course, this comes at the expense of portability to another EJB 3/JPA implementation.<br />A few of the Hibernate annotations are shown here.<br />You can and often will mix and match EJB 3/JPA and Hibernate annotations.<br />
  49. 49. Hibernate Annotations Cont.<br />On the @Entity annotation Hibernate annotations allow for the addition of many additional parameters.<br />For example, to make an entity immutable or to set the locking strategy requires the use of Hibernate Annotation extensions.<br />Unfortunately, the use of JPA’s @Entity annotation is still required.<br />Therefore, use of many of the native Hibernate annotations which collide with the JPA annotations requires the explicit reference in the annotation.<br />@Entity<br />@org.hibernate.annotations.Entity(mutable=false, optimisticLock=OptimisticLockType.VERSION)<br />public class Team {<br /> ...<br />}<br />
  50. 50. Hibernate Annotations Cont.<br />Direct field versus property access (using getters/setters) is determined by the position of the annotation in JPA; whether the field or method is annotated.<br />The access type can be made explicit using the @AccessType Hibernate annotation.<br />Properties that are derived by SQL formula require the @org.hibernate.annotations.Formula annotation.<br />@org.hibernate.annotations.AccessType(&quot;field&quot;)<br />@org.hibernate.annotations.Formula(&quot;hits/atBats&quot;)<br />private double battingAverage;<br />
  51. 51. Hibernate Annotations Cont.<br />While Hibernate will infer the data type using reflection. To override the default type, use the @org.hibernate.annotations.Type.<br />As mentioned earlier, Hibernate offers many more identifier generator strategies.<br />To use a Hibernate generator, use the @org.hibernate.annotations.GenericGenerators annotation.<br />@Type(type=&quot;double&quot;)<br />private int atBats;<br />@Id @GeneratedValue(generator=&quot;hibseq&quot;)<br />@GenericGenerator(name=&quot;hibseq&quot;, strategy = &quot;seqhilo&quot;,<br /> parameters = {<br /> @Parameter(name=&quot;max_lo&quot;, value = &quot;5&quot;),<br /> @Parameter(name=&quot;sequence&quot;, value=&quot;heybabyhey&quot;)<br /> }<br />)<br />public Integer getId() {<br />
  52. 52. Hibernate Annotations Cont.<br />While EJB 3/JPA does provide for a fetch strategy, Hibernate provides many more fetch modes and lazy loading options.<br />The @LazyToOne, @LazyCollection and @Fetch Hibernate annotations provide more detail specificity with regard to laziness and fetching strategy.<br />The @LazyToOne annotation defines the laziness option for @ManyToOne and @OneToOne associations<br />The @LazyCollection annotation defines the laziness option on @ManyToMany and @OneToMany associations. <br />The @Fetch annotation defines the fetching strategy used to load an association which can be set as SELECT, SUBSELECT or JOIN.<br />As with entities, when working with associated collections, Hibernate also provides many more mapping options.<br />The batch size for collections, where clause, SQL order, immutability, and more options can be established with Hibernate annotations.<br />
  53. 53. Hibernate Annotations Cont.<br />Hibernate also offers far more cascading styles than does JPA. Use Hibernate’s @Cascade annotation to specify a Hibernate cascading style.<br />JPA does not specify a cache or caching strategy.<br />To use Hibernate’s second level cache, use the @Cache annotation to designated second level cache and how it operates.<br />Lastly, Hibernate also supports many features on queries that require the use of query hints with JPA’s named query annotations.<br />@Entity<br />@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)<br />public class Team {<br /> ...<br />}<br />@org.hibernate.annotations.NamedQuery(name = &quot;getHomeRunHitters&quot;,<br /> query = &quot;from Batter where homeRuns &gt; :homeruns&quot;, <br /> comment=&quot;myComment&quot;, <br /> timeout=60)<br />
  54. 54. Summary<br />JDK 5.0 introduced annotations to the Java programming language.<br />Annotations put meta information or metadata into the Java code.<br />Annotations are a form of attribute-oriented programming.<br />The Hibernate Annotations package, used on top of the Hibernate Core, allows you to use metadata to replace or augment the XML mapping file.<br />In order to use Hibernate annotations, additional Hibernate JAR files are required.<br />A Java 5 environment is required in order to take advantage of Hibernate Annotations.<br />Hibernate Annotations were introduced with Hibernate Core 3.<br />Hibernate is considered an implementation of JPA. As such it offers EJB 3/JPA annotations.<br />The intent of using annotations is to remove (or at least greatly reduce) the number and size of the Hibernate mapping files.<br />When using Hibernate annotations, you use Hibernate annotations configuration when establishing the session factory.<br />The Hibernate API or general configuration do not change with using annotations.<br />
  55. 55. Thank you for coming!<br />I hoped you learned something today about<br />A Java 5 environment is required in order to take advantage of Hibernate Annotations.<br />Hibernate is considered an implementation of JPA. As such it offers EJB 3/JPA annotations.<br />The intent of using annotations is to remove (or at least greatly reduce) the number and size of the Hibernate mapping files.<br />In order to use Hibernate annotations, additional Hibernate JAR files are required.<br />When using Hibernate annotations, you use Hibernate annotations configuration when establishing the session factory.<br />The AnnotationConfiguration class is defined in org.hibernate.cfg and extends org.hibernate.cfg.Configuration.<br />Therefore the same Configuration API works with AnnotationConfiguration.<br />

×