Java Annotations

  • 8,081 views
Uploaded on

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

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.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
  • good
    Are you sure you want to
    Your message goes here

  • Are you sure you want to
    Your message goes here

  • Are you sure you want to
    Your message goes here
No Downloads

Views

Total Views
8,081
On Slideshare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
0
Comments
3
Likes
34

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Annotations
    2008 Intertech Oxygen Blast
  • 2. Before we begin…
    Good afternoon and welcome! My name is Jim White.
    Have you used WebEx before???
    A quick introduction to our meeting framework may be in order.
    As we continue the talk, please use the WebEx Q&A facility to submit questions.
    Technical difficulties – please email
    Doug Laing at DLAING@intertech.com
    Dan McCabe at DMCCABE@intertech.com
    - or call
    651-994-8558
  • 3. Who is this guy?
    Jim White – jwhite@intertech.com
    Author J2ME, Java in Small Things – 2002, Manning
    International Speaker
    Including JavaOne
    Contributor to many journals including:
    JDJ
    DevX.com
    JavaPro
    Consultant, engineer and architect with several companies
    Most recently - Senior Technical Architect at Target Corp.
  • 4. Objectives
    The objectives for today’s talk are to learn about Hibernate Annotations.
    The pros/cons of using annotations
    How to setup and configure Hibernate Annotations
    How to apply Hibernate Annotations in your code to replace (or augment) Hibernate XML Mapping files
    To understand the relationship of Hibernate Annotations to the Java Persistence API (JPA)
    An understanding of Hibernate (API, config, mapping) is expected.
    This material will be available to you on-line at: www.intertech.com
    Any questions before we begin?
  • 5. Metadata
    JDK 5.0 introduced annotations to the Java programming language.
    Annotations put meta information or metadata into the Java code.
    This metadata does not directly affect the programs meaning or semantics.
    Instead, metadata affects the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program.
    Annotations can be read from source files, class files, or reflectively at run time.
  • 6. Metadata Cont.
    Annotations are a form of attribute-oriented programming.
    Attribute-oriented programming is a program-level marking or “annotating” technique.
    Javadocs include forms of attribute-oriented programming.
    For example, the @deprecated Javadoc tag is metadata that indicates that the method should no longer be used.
    Other programming environments such as C# have had them since the language was formed.
    Java has had precursors to annotation for some time.
    XDoclet was a popular means to annotate Java source code with meta-information in order to automatically create deployment descriptors, etc.
  • 7. Metadata Cont.
    In general, annotations allow metadata, like that in Hibernate mapping files, to be put next to the information it describes.
    That is in the class files next to the code it describes.
    This is opposed to having this information in some separate file (the .hbm.xml file).
    The reason for annotation is that when you update the class, you probably also want to update the information that describes the class.
    The Hibernate Annotations package, used on top of the Hibernate Core, allows you to use metadata to replace or augment the XML mapping file.
  • 8. Metadata Cont.
    Hibernate Annotations were introduced with Hibernate Core 3.
    A Java 5 environment is required in order to take advantage of Hibernate Annotations.
    Java Persistence Architecture API (JPA) is a Java specification for accessing, persisting and managing data between Java objects and the relational database.
    JPA was defined as part of the EJB 3.0 specification as a replacement to the EJB 2 Container Managed Entity Beans.
    In the Java community, JPA now sets the “standard industry approach” for object-relational mapping.
    It is the JPA specification that defines object/relational mapping metadata syntax and semantics for ORM annotations.
    Hibernate is considered an implementation of JPA. As such it offers EJB 3/JPA annotations.
  • 9. Annotations Pros/Cons
    Before exploring Annotations in Hibernate, a few of the pros/cons should be discussed.
    Java, and specifically Java EE, is embracing annotations aggressively.
    They are, or soon will be, everywhere in your applications.
    The EJB 3.0 and Java Persistence standards have fully embraced annotations.
    Expert groups that are pushing the migration to annotations advise of certain limitations and considerations before adopting annotations.
    The often sighted “pro” of annotation is that they are attached to the program artifacts they describe.
    This gives the metadata information relevance that is not always there (or clear) when viewed in an XML file.
    However, when searching an application for all the applicable and like program characteristics, an XML document makes the search concise.
  • 10. Annotations Pros/Cons Cont.
    Annotations can replace XML deployment descriptors and configurations.
    Annotations are typically much simpler to code than XML.
    XML is not always the easiest of documents to read or maintain and it is often very verbose.
    However, some configuration data changes with each deployment.
    Consider what changes as you move your application from dev to test to stage to production platforms.
    Annotations, as part of the Java code, can create significant issues when the configuration changes per platform.
    Dev
    Test
    Stage
    Prod
  • 11. Annotations Pros/Cons Cont.
    Some configuration/deployment information can now be shared across programming environments.
    Take for example Hibernate. nHibernate is now a framework for the .NET environment.
    In time, could the XML configuration files of many frameworks like Hibernate be used cross-platform?
    Annotations, as part of the actual source code, will not support and promote any cross-platform sharing.
  • 12. Annotations Pros/Cons Cont.
    Annotations are part of the source code.
    This can be a pro in the sense that the annotations are compiled right into the class files.
    Since the annotations are with the code, an incorrect or stale XML file cannot be accidentally used to configure the application.
    On the other hand, annotations can only be read at runtime.
    Therefore, they cannot be added as additional XML can be at runtime.
    When only the bytecode is available, annotations may create difficulties.
    In this case, an XML file allows for application changes without the source.
    Annotations cannot be validated in the same way that XML can be validated.

    @Entity
    @Table(name = "Player", schema = "MLB")
    public abstract class BallPlayer {


    <hibernate-mapping package="com.intertech.domain">
    <class name="BallPlayer" table="Player" abstract="true">
    <id name="id">

  • 13. Hibernate Annotation Libraries
    In order to use Hibernate annotations, additional Hibernate JAR files are required.
    Download the Hibernate Annotations distribution from Hibernate Web site.
    www.hibernate.org
    Extract the JAR files listed in the table below. Make these JARs available to your runtime and applicable IDE environment.
  • 14. Configuring Hibernate Annotations
    When using Hibernate annotations, you use Hibernate annotations configuration when establishing the session factory.
    This is in contrast to using the Hibernate Configuration object to load all the configuration information.
    The AnnotationConfiguration class is defined in org.hibernate.cfg and extends org.hibernate.cfg.Configuration.
    Therefore the same Configuration API works with AnnotationConfiguration.
    SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
    SessionFactory sessionFactory = new Configuration(). configure().buildSessionFactory();
  • 15. Configuring Hibernate Annotations Cont.
    The intent of using annotations is to remove (or at least greatly reduce) the number and size of the Hibernate mapping files.
    The emphasis should be to move Hibernate mapping information into classes via annotation.
    However, Hibernate must be signaled as to which classes are domain classes and which classes to examine for annotations.
    In the Hibernate configuration file (hibernate.cfg.xml), the <mapping> element is used to specify domain classes to check for annotations.
    This can be done by class or by package (suggesting all the classes in the package may have annotations and should be checked).
    Hibernate mapping files can still be specified and used in the Hibernate configuration file (hibernate.cfg.xml).
    <mapping class="com.intertech.domain.BallPlayer" />
    <mapping package="com.intertech.business.model"/>
  • 16. Configuring Hibernate Annotations Cont.
    While you can use both annotations and mapping files, you should not use both annotations and a Hibernate mapping file for the same entity.
    To ease the migration process and allow mapping files and annotations to coexist, Hibernate will not complain when there are duplicate mappings.
    Hibernate mapping files have precedent over annotations by default.
    You can change the default in the Hibernate configuration file by setting the hibernate.mapping.precedence property.
    It defaults to “hbm, class” but can be set to “class, hbm”.
    Removing either hbm or class from the property option, removes that form of configuration.
    Again, however, this override mechanism was implemented for ease in migration to annotations. Dual mappings should be avoided.
    hibernate.connection.username=sa
    hibernate.dialect=org.hibernate.dialect.HSQLDialect
    hibernate.mapping.precedence=class, hbm
  • 17. Configuring Hibernate Annotations Cont.
    If not specified in the hibernate.cfg.xml, the annotated classes/packages can also be specified programmatically on the Configuration object.
    SessionFactory sessionFactory = new AnnotationConfiguration(). configure().addPackage("com.intertech.business.model"). addAnnotatedClass(com.intertech.domain.BallPlayer.class). buildSessionFactory();
  • 18. Configuring Hibernate Annotations Cont.
    No other configuration changes are required to use annotations. Hibernate properties and other configurations remain unchanged.
    Annotations do not require any changes in the way the Hibernate API behaves or is used.
  • 19. EJB3/JPA Annotations
    The title of this section might have confused you. EJBs? JPA? Where did that come from?
    Remember, the EJB 3.0 specification (that includes JPA) defines the metadata syntax and semantics.
    Hibernate, as a JPA implementation, uses this syntax.
    So when learning “Hibernate Annotations” you must first learn EJB3/JPA annotations.
    There are additional Hibernate specific annotations called Hibernate annotation extensions. These are covered later.
    The fact that there is a Java specification for the metadata is good.
    It ultimately provides more portability among ORM capabilities.
    However, the fact that many features/mappings available in Hibernate require Hibernate specific annotations potentially degrades portability.
    Having EBJ3/JPA annotations and Hibernate annotations can also confuse developers new to annotations.
  • 20. Exploring Annotations
    Perhaps the best way to explore the JPA and Hibernate annotations is by example.
  • 21. Exploring Annotations Cont.
    An exhaustive look at all the annotations is not possible in this limited time.
    This example should provide an example of the more widely used mappings in Hibernate
    Entity mapping
    Many-to-one (BallPlayer to Team)
    One-to-one (Team to Stadium)
    And Inheritance mapping (BallPlayer, Batter, Pitcher)
  • 22. Entity Hibernate XML Mapping
    <hibernate-mapping package="com.intertech.domain">
    <class name="Team">
    <id name="id">
    <generator class="sequence">
    <param name="sequence">common_seq</param>
    </generator>
    </id>
    <property name="nickname" />
    <property name="founded" />
    <property name="mascot" />

    </class>
    </hibernate-mapping>
  • 23. Entity Annotations
    To define a POJO or JavaBean as a persistent entity, use the @Entity annotation.
    @Table annotation allows you to explicitly specify the table to which the entity is mapped.
    If not provided, the table name defaults to the name of the class.
    Schema and catalog optional attributes can be specified on the @Table annotation.
    import javax.persistence.Entity;
    @Entity
    public class Team {
    private long id;
    private String nickname;

    }
    import javax.persistence.Entity;
    import javax.persistence.Table;
    @Entity
    @Table(name = "Player", schema="MLB")
    public abstract class BallPlayer {
    private long id;

    }
  • 24. Property Annotations
    By default, all non-static properties of an entity are mapped by default. No annotation is required to map properties.
    If you do not want a property mapped, use the @Transient annotation to exclude the property.
    Explicitly, you can use @Basic to annotate a property for mapping. This allows attributes like fetching strategies to be applied.
    Use the @Column annotation to specify the database column name when the name does not match the property name.
    @Entity
    @Table(name = "Player", schema="MLB")
    public abstract class BallPlayer {
    private long id;
    @Basic
    private String name; //default mapping
    private String nickname;
    @Column(name = "date_of_birth")
    private Calendar dob;
    @Transient
    private int userInterfaceHandle;

    }
  • 25. Property Annotations Cont.
    Attributes of updatable and insertable on the @Column annotation allow properties to be protected from modification.
    @Column(updatable=false, insertable=false)
  • 26. Identifier Annotations
    The @Id annotation should be applied to the identifier property.
    The @GeneratedValue annotation allows you specify the Hibernate generator when used.
    The EJB3/JPA specification defines only four generators (it calls these generator strategies).
    The Hibernate extension annotations allow Hibernate’s additional generators to be used.
  • 27. Identifier Annotations Cont.
    By default, the strategy defaults to AUTO.
    When using a SEQUENCE or TABLE generator, use the proper annotation to specify the identifier in the database.
    The sequence generator annotation is shown below. Use @TableGenerator annotation for the Table strategy.
    When the name of the identifier property and column do not align, the @Column can again be used to explicitly specify the id column.
    @Entity
    public class Team {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "myGenerator")
    @SequenceGenerator(name = "myGenerator", sequenceName = "common_seq")
    private long id;

    }
  • 28. Access via Annotations
    Field versus getter/setter (property) access is defined by where the annotation is placed relative to the code.
    Furthermore, an annotated entity inherits the default form (field versus property access) based on the position of the mandatory @Id annotation.
    So if @Id is has been declared on the field, not a getter method, all other properties are accessed by getter and setter too.
    //field access (for identifier and all implicit property mapping)
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="common_seq")
    private long id
    //versus method access (for id and all implicit property mappings)
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="myGenerator")
    @SequenceGenerator(name="myGenerator", sequenceName="common_seq")
    public long getId() {
    return id;
    }
  • 29. Inheritance Annotations
    Recall that Hibernate has three ways to map inherited classes to database tables.
    A table is mapped to each concrete class in an inheritance hierarchy. This is called the table per concrete class strategy.
    A table is mapped to each class and subclass in an inheritance hierarchy. This is called the table per subclass strategy.
    The entire class hierarchy is mapped to a single table. This is called the table per hierarchy strategy.
    JPA annotations support the same three ways to map inherited classes, but uses different names for the strategies.
  • 30. Inheritance Annotations Cont.
    The table per concrete mapping is called the table per class strategy in JPA.
  • 31. Inheritance Annotations Cont.
    </hibernate-mapping>
    <hibernate-mapping package="com.intertech.domain">
    <class name="Pitcher" table="Pitcher">
    <id name="id">
    <generator class="sequence">
    <param name="sequence">common_seq</param>
    </generator>
    </id>
    <property name="name" />
    <property name="dob" column="date_of_birth" />
    <property name="birthCity" column="city_of_birth" />
    <property name="uniformNumber" column="uniform_number" />
    <property name="handed" column="throws"/>
    <property name="wins"/>
    <property name="losses"/>
    <property name="earnedRunAverage" column="earned_run_average"/>

    </class>
    </hibernate-mapping>
    <hibernate-mapping package="com.intertech.domain">
    <class name="Batter" table="Batter">
    <id name="id">
    <generator class="sequence">
    <param name="sequence">common_seq</param>
    </generator>
    </id>
    <property name="name" />
    <property name="dob" column="date_of_birth" />
    <property name="birthCity" column="city_of_birth" />
    <property name="uniformNumber" column="uniform_number" />
    <property name="position" column="pos"/>
    <property name="bats"/>
    <property name="atBats" column="at_bats"/>
    <property name="hits"/>
    <property name="homeRuns" column="home_runs"/>

    </class>
    </hibernate-mapping>
  • 32. Inheritance Annotations Cont.
    @Entity
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public abstract class BallPlayer{
    ...
    }
    @Entity
    @Table(name="Batter") //explicit but not required
    public class Batter extends BallPlayer {
    ...
    }
    @Entity
    @Table(name="Pitcher") //explicit but not required
    public class Pitcher extends BallPlayer {
    ...
    }
  • 33. Inheritance Annotations Cont.
    The table per subclass mapping is called the joined strategy in JPA.
  • 34. Inheritance Annotations Cont.
    <hibernate-mapping package="com.intertech.domain">
    <class name="BallPlayer" table="Player">
    <id name="id">
    <generator class="sequence">
    <param name="sequence">common_seq</param>
    </generator>
    </id>
    <property name="name" />
    <property name="dob" column="date_of_birth" />
    <property name="birthCity" column="city_of_birth" />
    <property name="uniformNumber" column="uniform_number" />

    <joined-subclass name="Batter">
    <key column="id" />
    <property name="position" column="pos" />
    <property name="bats" />
    <property name="atBats" column="at_bats" />
    <property name="hits" />
    <property name="homeRuns" column="home_runs" />
    </joined-subclass>
    <joined-subclass name="Pitcher">
    <key column="id" />
    <property name="handed" column="throws" />
    <property name="wins" />
    <property name="losses" />
    <property name="earnedRunAverage" column="earned_run_average" />
    </joined-subclass>
    </class>
    </hibernate-mapping>
  • 35. Inheritance Annotations Cont.
    @Entity
    @Table(name="Player")
    @Inheritance(strategy = InheritanceType.JOINED)
    public abstract class BallPlayer{
    ...
    }
    @Entity
    public class Batter extends BallPlayer {
    ...
    }
    @Entity
    public class Pitcher extends BallPlayer {
    ...
    }
  • 36. Inheritance Annotations Cont.
    The last inheritance mapping option is the table per hierarchy strategy. In JPA, this is called aptly the single table strategy.
  • 37. Inheritance Annotations Cont.
    <hibernate-mapping package="com.intertech.domain">
    <class name="BallPlayer" table="Player">
    <id name="id">
    <generator class="sequence">
    <param name="sequence">common_seq</param>
    </generator>
    </id>
    <discriminator column="player_type"/>
    <property name="name" />
    <property name="dob" column="date_of_birth" />
    <property name="birthCity" column="city_of_birth" />
    <property name="uniformNumber" column="uniform_number" />
    ….
    <subclass name="Batter" discriminator-value="B">
    <property name="position" column="pos" />
    <property name="bats" />
    <property name="atBats" column="at_bats" />
    <property name="hits" />
    <property name="homeRuns" column="home_runs" />
    </subclass>
    <subclass name="Pitcher" discriminator-value="P">
    <property name="handed" column="throws" />
    <property name="wins" />
    <property name="losses" />
    <property name="earnedRunAverage" column="earned_run_average" />
    </subclass>
    </class>
    </hibernate-mapping>
  • 38. Inheritance Annotations Cont.
    @Entity
    @Table(name="Player")
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="player_type", discriminatorType=DiscriminatorType.STRING)
    public abstract class BallPlayer{
    ...
    }
    @Entity
    @DiscriminatorValue("B")
    public class Batter extends BallPlayer {
    ...
    }
    @Entity
    @DiscriminatorValue("P")
    public class Pitcher extends BallPlayer {
    ...
    }
  • 39. One-to-one Association Annotations
    In the example domain model, Team has a one-to-one relationship to Stadium instances.
    In the Stadium.hbm.xml mapping file, this was mapped in XML as shown below.
    To map this entity to entity association with JPA annotations, on the Stadium entity, use the @OneToOne annotation.
    <many-to-one name="team" class="Team" column="team_id“ unique="true" />
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "team_id")
    private Team team;
  • 40. One-to-one Association Annotations Cont.
    Note the cascading style for transitive persistence can be specified on the association annotation.
    JPA’s cascading styles are similar but identical to Hibernate’s cascading styles.
    The @JoinColumn specifies the foreign key column in the Team table used to join to the Stadium table.
    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”.
    In this case, that would mean that Team would need a foreign key column of HOMEFIELD_ID.
  • 41. One-to-one Association Annotations Cont.
    Again, associations in Java can be bidirectional. Without any other annotations in the Team class, the relationship is unidirectional.
    To make the relationship bidirectional, add the @OneToOne annotation to Team.
    The mappedBy attribute has the effect of the property-ref attribute in the <one-to-one> element in the Hibernate XML mapping (shown below).
    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.
    @OneToOne(mappedBy = "team")
    private Stadium homeField;
    <one-to-one name="homeField" class="Stadium" property-ref="team“ cascade="all" />
  • 42. Many-to-one Association Annotation
    BallPlayers have a many-to-one relationship to Team objects in the current business domain model.
    From the BallPlayer to Team perspective, the many-to-one association to a Team object was mapped with the XML below.
    Using JPA annotations, this same relationship is accomplished with a @ManyToOne annotation in the BallPlayer class.
    <many-to-one name="team" column="team_id"
    class="com.intertech.domain.Team" />
    @ManyToOne()
    @JoinColumn()
    private Team team;
  • 43. Many-to-one Association Annotation Cont.
    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.
    As in the @JoinColumn annotation for the one-to-one mapping, this can be made explicit if the default does not work.
    @JoinColumn(name=”owning_team_id”)
  • 44. Many-to-one Association Annotation Cont.
    To make this association bidirectional, Team must map a collection of BallPlayers.
    The XML mapping for a set of BallPlayers is shown below.
    Here is the JPA annotation in the Team class to implement the same the association from Tam back to the BallPlayer.
    The mappedBy parameter is equivalent to the inverse attribute in the XML mapping.
    <set name="players" inverse="true">
    <key column="team_id" />
    <one-to-many class="com.intertech.domain.BallPlayer" />
    </set>
    @OneToMany(mappedBy="team")
    private Set<BallPlayer> players = new HashSet<BallPlayer>();
  • 45. Query Annotations
    Queries can be mapped in the class files as well.
    Annotated named queries in entity class files are considered “global” to the session factory.
    Therefore, a query defined in BallPlayer is available by its name in other classes too.
    Therefore, the query name must be unique.
  • 46. Query Annotations Cont.
    Use the @NamedQuery annotation at the top of an annotated entity.
    It must be defined outside of the actual class definition.
    Query hints such as timeout and fetch size can also be provided as parameters.
    @NamedQuery(name="getHomeRunHitters",query="from Batter where homeRuns > :homeruns")
    @Entity
    @Table(name="Player")
    @Inheritance(strategy = InheritanceType.SINGLE_TABLE)
    @DiscriminatorColumn(name="player_type", discriminatorType=DiscriminatorType.STRING)
    public abstract class BallPlayer{
    ...
    }
    @NamedQuery(name = "getHomeRunHitters",
    query = "from Batter where homeRuns > :homeruns",
    hints = {
    @QueryHint(name = "org.hibernate.comment", value = "My Comment"),
    @QueryHint(name = "org.hibernate.timeout", value = "60") })
  • 47. Query Annotations Cont.
    Executing an annotated named query is no different than executing a named query defined in a mapping file.
    In a similar fashion, named native queries can also be annotated in class files.
    Query query = session.getNamedQuery("getHomeRunHitters");
    List list = query.setInteger("homeruns", 5).list();
    @NamedNativeQuery(name = "getHomeRunHittersAndTeam",
    resultClass = Batter.class,
    query = "select * from Player p join Team t on p.team_id = t.id where p.player_type = 'B' and p.home_runs > :homeruns")
  • 48. Hibernate Annotations
    Hibernate provides a set of its own annotations.
    The Hibernate annotations extend the EJB 3/JPA annotations.
    That is Hibernate annotations are built on top of the JPA Annotations.
    The Hibernate annotations provide a means to implement features of Hibernate’s XML mapping capabilities via annotations.
    Not all of Hibernate’s mapping features are supported in the EJB 3/JPA specification.
    Of course, this comes at the expense of portability to another EJB 3/JPA implementation.
    A few of the Hibernate annotations are shown here.
    You can and often will mix and match EJB 3/JPA and Hibernate annotations.
  • 49. Hibernate Annotations Cont.
    On the @Entity annotation Hibernate annotations allow for the addition of many additional parameters.
    For example, to make an entity immutable or to set the locking strategy requires the use of Hibernate Annotation extensions.
    Unfortunately, the use of JPA’s @Entity annotation is still required.
    Therefore, use of many of the native Hibernate annotations which collide with the JPA annotations requires the explicit reference in the annotation.
    @Entity
    @org.hibernate.annotations.Entity(mutable=false, optimisticLock=OptimisticLockType.VERSION)
    public class Team {
    ...
    }
  • 50. Hibernate Annotations Cont.
    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.
    The access type can be made explicit using the @AccessType Hibernate annotation.
    Properties that are derived by SQL formula require the @org.hibernate.annotations.Formula annotation.
    @org.hibernate.annotations.AccessType("field")
    @org.hibernate.annotations.Formula("hits/atBats")
    private double battingAverage;
  • 51. Hibernate Annotations Cont.
    While Hibernate will infer the data type using reflection. To override the default type, use the @org.hibernate.annotations.Type.
    As mentioned earlier, Hibernate offers many more identifier generator strategies.
    To use a Hibernate generator, use the @org.hibernate.annotations.GenericGenerators annotation.
    @Type(type="double")
    private int atBats;
    @Id @GeneratedValue(generator="hibseq")
    @GenericGenerator(name="hibseq", strategy = "seqhilo",
    parameters = {
    @Parameter(name="max_lo", value = "5"),
    @Parameter(name="sequence", value="heybabyhey")
    }
    )
    public Integer getId() {
  • 52. Hibernate Annotations Cont.
    While EJB 3/JPA does provide for a fetch strategy, Hibernate provides many more fetch modes and lazy loading options.
    The @LazyToOne, @LazyCollection and @Fetch Hibernate annotations provide more detail specificity with regard to laziness and fetching strategy.
    The @LazyToOne annotation defines the laziness option for @ManyToOne and @OneToOne associations
    The @LazyCollection annotation defines the laziness option on @ManyToMany and @OneToMany associations.
    The @Fetch annotation defines the fetching strategy used to load an association which can be set as SELECT, SUBSELECT or JOIN.
    As with entities, when working with associated collections, Hibernate also provides many more mapping options.
    The batch size for collections, where clause, SQL order, immutability, and more options can be established with Hibernate annotations.
  • 53. Hibernate Annotations Cont.
    Hibernate also offers far more cascading styles than does JPA. Use Hibernate’s @Cascade annotation to specify a Hibernate cascading style.
    JPA does not specify a cache or caching strategy.
    To use Hibernate’s second level cache, use the @Cache annotation to designated second level cache and how it operates.
    Lastly, Hibernate also supports many features on queries that require the use of query hints with JPA’s named query annotations.
    @Entity
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    public class Team {
    ...
    }
    @org.hibernate.annotations.NamedQuery(name = "getHomeRunHitters",
    query = "from Batter where homeRuns > :homeruns",
    comment="myComment",
    timeout=60)
  • 54. Summary
    JDK 5.0 introduced annotations to the Java programming language.
    Annotations put meta information or metadata into the Java code.
    Annotations are a form of attribute-oriented programming.
    The Hibernate Annotations package, used on top of the Hibernate Core, allows you to use metadata to replace or augment the XML mapping file.
    In order to use Hibernate annotations, additional Hibernate JAR files are required.
    A Java 5 environment is required in order to take advantage of Hibernate Annotations.
    Hibernate Annotations were introduced with Hibernate Core 3.
    Hibernate is considered an implementation of JPA. As such it offers EJB 3/JPA annotations.
    The intent of using annotations is to remove (or at least greatly reduce) the number and size of the Hibernate mapping files.
    When using Hibernate annotations, you use Hibernate annotations configuration when establishing the session factory.
    The Hibernate API or general configuration do not change with using annotations.
  • 55. Thank you for coming!
    I hoped you learned something today about
    A Java 5 environment is required in order to take advantage of Hibernate Annotations.
    Hibernate is considered an implementation of JPA. As such it offers EJB 3/JPA annotations.
    The intent of using annotations is to remove (or at least greatly reduce) the number and size of the Hibernate mapping files.
    In order to use Hibernate annotations, additional Hibernate JAR files are required.
    When using Hibernate annotations, you use Hibernate annotations configuration when establishing the session factory.
    The AnnotationConfiguration class is defined in org.hibernate.cfg and extends org.hibernate.cfg.Configuration.
    Therefore the same Configuration API works with AnnotationConfiguration.