CHAPTER 6 n MAPPING WITH ANNOTATIONS (Submit web site) 101 n

CHAPTER 6 n MAPPING WITH ANNOTATIONS 101 n MAPPING WITH ANNOTATIONS 101 public void setPages(int pages) { this.pages = pages; } } As you can see, this is a POJO. We are going to annotate this class as we go along, explaining the concepts behind annotation. Entity Beans with @Entity The first step is to annotate the Book class as an EJB 3 entity bean. With traditional EJB, we would have added an EJB marker interface to mark the class as an entity bean. Instead, we add the @Entityannotation to the Bookclass, as follows: package com.hibernatebook.annotations; import javax.persistence.*; @Entity public class Book The EJB 3 standard annotations are contained in the javax.persistence package, so we import the appropriate annotations (here we will use wildcard imports to keep the listings short, but in the downloadable source code accompanying this chapter, we use explicit imports such as import javax.persistence.Entity; annotations are imported in exactly the same way as the ordinary interfaces that they resemble). The @Entity annotation marks this class as an entity bean, so it must have a no-argument constructor that is visible with at least protected scope. Hibernate supports package scope as the minimum, but you lose portability to other EJB 3 containers if you take advantage of this. Other EJB 3 rules for an entity bean class are that the class must not be final, and that the entity bean class must be concrete. Many of the rules for EJB 3 entity bean classes and Hibernate 3 persistent objects are the same partly because the Hibernate team had much input into the EJB 3 design process, and partly because there are only so many ways to design a relatively unobtrusive object-relational persistence solution. As you can see, although we did have to add the import statement and the annotations, we have not had to change the rest of the code. The POJO is essentially unchanged. Primary Keys with @Id and @GeneratedValue Each entity bean has to have a primary key, which you annotate on the class with the @Id annotation. Typically, the primary key will be a single field, though it can also be a composite of multiple fields. The placement of the @Id annotation determines the default access strategy that Hibernate will use for the mapping. If the annotation is applied to a field as shown in Listing 6-4, then field access will be used.
Note: If you are looking for reliable webhost to maintain and run your java application check Vision java hosting services

Leave a Reply