Archive for April, 2007

108 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER (Mac os x web server)

Friday, April 20th, 2007

108 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS public Account(String description) { this.description = description; } protected Account() { } @EmbeddedId public AccountPk getId() { return this.id; } public String getDescription() { return this.description; } public void setId(AccountPk id) { this.id = id; } public void setDescription(String description) { this.description = description; } public static class AccountPk { // … } } Finally, the use of the @IdClass and @Idannotations allows us to map the compound primary key class using properties of the entity itself corresponding to the names of the properties in the primary key class. The names must correspond (there is no mechanism for overriding this), and the primary key class must honor the same obligations as with the other two techniques. The only advantage to this approach is its ability to hide the use of the primary key class from the interface of the enclosing entity. The @IdClassannotation takes a value parameter of Classtype, which must be the class to be used as the compound primary key. The fields that correspond to the properties of the primary key class to be used must all be annotated with @Id note in Listing 6-8 that the getCode() and getNumber()methods of the Accountclass are so annotated, and the AccountPkclass is not mapped as @Embeddable, but it is supplied as the value of the @IdClass annotation.
Note: In case you are looking for affordable and reliable webhost to host and run your business application check Vision ftp web hosting services

CHAPTER 6 n MAPPING WITH (Ftp web hosting) ANNOTATIONS 107 n

Friday, April 20th, 2007

CHAPTER 6 n MAPPING WITH ANNOTATIONS 107 n MAPPING WITH ANNOTATIONS 107 public Integer getNumber() { return this.number; } public void setNumber(Integer number) { this.number = number; } public void setCode(String code) { this.code = code; } public int hashCode() { int hashCode = 0; if( code != null ) hashCode ^= code.hashCode(); if( number != null ) hashCode ^= number.hashCode(); return hashCode; } public boolean equals(Object obj) { if( !(obj instanceof AccountPk) ) return false; AccountPk target = (AccountPk)obj; return ((this.code == null) ? (target.code == null) : this.code.equals(target.code)) && ((this.number == null) ? (target.number == null) : this.number.equals(target.number)); } } } The next most natural approach is the use of the @EmbeddedId tag. Here, the primary key class cannot be used in other tables since it is not an @Embeddable entity, but it does allow us to treat the key as a single attribute of the Account class (in Listings 6-7 and 6-8, the implementation of AccountPk is identical to that in Listing 6-6, and is thus omitted for brevity). Note that in Listings 6-7 and 6-8, the AccountPk class is not marked as @Embeddable. Listing 6-7. Using the @EmbeddedId Annotation to Map a Compound Primary Key package com.hibernatebook.annotations; import javax.persistence.*; @Entity public class Account { private String description; private AccountPk id;
Note: In case you are looking for affordable webhost to host and run your web application check Vision http web server services

106 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER (Php web hosting)

Thursday, April 19th, 2007

106 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS Listing 6-6. Using the @Id and @Embeddable Annotations to Map a Compound Primary Key package com.hibernatebook.annotations; import javax.persistence.*; @Entity public class Account { private String description; private AccountPk id; public Account (String description) { this.description = description; } protected Account() { } @Id public AccountPk getId() { return this.id; } public String getDescription() { return this.description; } public void setId(AccountPk id) { this.id = id; } public void setDescription(String description) { this.description = description; } @Embeddable public static class AccountPk { private String code; private Integer number; public AccountPk() { } public String getCode() { return this.code; }
Note: If you are looking for high quality webhost to host and run your jsp application check Vision jsp web hosting services

CHAPTER 6 n MAPPING WITH (Make a web site) ANNOTATIONS 105 n

Thursday, April 19th, 2007

CHAPTER 6 n MAPPING WITH ANNOTATIONS 105 n MAPPING WITH ANNOTATIONS 105 schema: Allows the schema that the table resides within to be specified. table: The name of the table containing the primary key values. uniqueConstraints: Allows additional constraints to be applied to the table for schema generation. valueColumnName: Allows the column containing the primary key generation information for the current entity to be identified. Because the table can be used to contain the primary key values for a variety of entries, it is likely to contain a single row for each of the entities using it. It therefore needs its own primary key (pkColumnName), as well as a column containing the next primary key value to be used (pkColumnValue) for any of the entities obtaining their primary keys from it. Compound Primary Keys with @Id, @IdClass, or @EmbeddedId While the use of single column surrogate keys is advantageous for various reasons, you may sometimes be forced to work with business keys. When these are contained in a single column, you can use @Id without specifying a generation strategy (forcing the user to assign a primary key value before the entity can be persisted). However, when the primary key consists of multiple columns, you need to take a different strategy to group these together in a way that allows the persistence engine to manipulate the key values as a single object. You must create a class to represent this primary key. It will not require a primary key of its own, of course, but it must be a public class, must have a default constructor, must be serializable, and must implement hashCode() and equals()methods to allow the Hibernate code to test for primary key collisions (i.e., they must be implemented with the appropriate database semantics for the primary key values). Your three strategies for using this primary key class once it has been created are as follows: Mark it as @Embeddable and add to your entity class a normal property for it, marked with @Id. Add to your entity class a normal property for it, marked with @EmbeddableId. Add properties to your entity class for all of its fields, mark them with @Id, and mark your entity class with @IdClass, supplying the class of your primary key class. All these techniques require the use of an id class because Hibernate must be supplied with a primary key object when various parts of its persistence API are invoked. For example, you can retrieve an instance of an entity by invoking the Sessionobject s get() method, which takes as its parameter a single serializable object representing the entity s primary key. The use of @Id with a class marked as @Embeddable, as shown in Listing 6-6, is the most natural approach. The @Embeddable tag can be used for non primary key embeddable values anyway (@Embeddable is discussed in more detail later in the chapter). It allows you to treat the compound primary key as a single property, and it permits the reuse of the @Embeddable class in other tables.
Note: If you are looking for cheap and reliable webhost to host and run your web application check Vision coldfusion web hosting services

104 CHAPTER 6 n MAPPING (Personal web server) WITH ANNOTATIONS CHAPTER

Thursday, April 19th, 2007

104 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS Only the sequence generator name is mandatory the other attributes will take sensible default values but you should provide an explicit value for the sequenceNameattribute as a matter of good practice anyway. If not specified, the sequenceName value to be used is selected by the persistence provider (i.e., Hibernate or EJB 3). The other (optional) attributes are initialValue and allocationSize, which default to values of 1 and 50, respectively. Generating Primary Key Values with @TableGenerator The @TableGenerator annotation is used in a very similar way to the @SequenceGenerator annotation but because @TableGenerator manipulates a standard database table to obtain its primary key values, instead of using a vendor-specific sequence object, it is guaranteed to be portable between database platforms. nNote For optimal portability and optimal performance, you should not specify the use of a table generator, but instead use the @GeneratorValue(strategy=GeneratorType.AUTO) configuration, which allows the persistence provider to select the most appropriate strategy for the database in use. As with the sequence generator, the name attributes of @TableGenerator are mandatory and the other attributes are optional, with the table details being selected by the persistence provider. @Id @TableGenerator(name=”tablegen”, table=”ID_TABLE”, pkColumnName=”ID”, valueColumnName=”NEXT_ID”) @GeneratedValue(strategy=TABLE,generator=”tablegen”) public int getId() { return id; } The optional attributes are as follows: allocationSize: Allows the increment on the primary key value to be specified. catalog: Allows the catalog that the table resides within to be specified. initialValue: Allows the starting primary key value to be specified. pkColumnName: Allows the primary key column of the table to be identified. The table can contain the details necessary for generating primary key values for multiple entities. pkColumnValue: Allows the primary key for the row containing the primary key generation information to be identified.
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision j2ee hosting services

Best web design - CHAPTER 6 n MAPPING WITH ANNOTATIONS 103 n

Wednesday, April 18th, 2007

CHAPTER 6 n MAPPING WITH ANNOTATIONS 103 n MAPPING WITH ANNOTATIONS 103 AUTO: Hibernate decides which generator type to use, based on the database s support for primary key generation. IDENTITY: The database is responsible for determining and assigning the next primary key. SEQUENCE: Some databases support a SEQUENCEcolumn type. See the Generating Primary Key Values with @SequenceGenerator section later in the chapter. TABLE: This type keeps a separate table with the primary key values. See the Generating Primary Key Values with @TableGenerator section later in the chapter. You will notice that the available values for the strategy attribute do not exactly match the values for Hibernate s primary key generators for XML mapping. If you need to use Hibernate-specific primary key generation strategies, you can use some of the Hibernate extensions described at the end of this chapter but as always, you risk forfeiting portability of your application to other EJB 3 environments when taking advantage of Hibernate- specific features. For the Book class, we are going to use the default key generation strategy. Letting Hibernate determine which generator type to use makes your code portable between different databases. Because we want Hibernate to use property access to our POJO, we must annotate the getter method for the identifier, not the field that it accesses: @Id @GeneratedValue public int getId() { return id; } Generating Primary Key Values with @SequenceGenerator As noted in the section on the @Id tag, we can declare the primary key property as being generated by a database sequence. A sequence is a database object that can be used as a source of primary key values. It is similar to the use of an identity column type, except that a sequence is independent of any particular table and can therefore be used by multiple tables. To declare the specific sequence object to use and its properties, you must include an @SequenceGenerator annotation on the annotated field. Here s an example: @Id @SequenceGenerator(name=”seq1″,sequenceName=”HIB_SEQ”) @GeneratedValue(strategy=SEQUENCE,generator=”seq1″) public int getId() { return id; } Here, a sequence generation annotation named seq1 has been declared. This refers to the database sequence object called HIB_SEQ. The name seq1 is then referenced as the generator attribute of the @GeneratedValue annotation.
Note: In case you are looking for affordable and reliable webhost to host and run your business application check Vision ftp web hosting services

Web site directory - 102 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER

Wednesday, April 18th, 2007

102 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS Listing 6-4. A Class with Field Access import javax.persistence.*; @Entity public class Sample { @Id int id; public int getId() { return this.id; } public void setId(int id) { this.id = id; } } If instead the annotation is applied to the getter for the field, as shown in Listing 6-5, then property access will be used. Listing 6-5. The Same Class with Property Access import javax.persistence.*; @Entity public class Sample { int id; @Id public int getId() { return this.id; } public void setId(int id) { this.id = id; } } Here you can see one of the strengths of the annotations approach because the annotations are placed inline with the source code, information can be extracted from the context of the mapping in the code, allowing many mapping decisions to be inferred rather than stated explicitly which helps to further reduce the verbosity of the annotations. By default, the @Id annotation will automatically determine the most appropriate primary key generation strategy to use you can override this by also applying the @GeneratedValue annotation. This takes a pair of attributes: strategy and generator. The strategyattribute must be a value from the javax.persistence.GeneratorTypeenumeration. If you do not specify a generator type, the default is AUTO. There are four different types of primary key generators on GeneratorType, as follows:
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision personal web hosting services

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

Tuesday, April 17th, 2007

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

100 CHAPTER 6 n (Web site traffic) MAPPING WITH ANNOTATIONS CHAPTER

Tuesday, April 17th, 2007

100 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS The set of example classes represents a publisher s catalog of books. You ll start with a single class, Book, which has no annotations or mapping information. For this example s purposes, you do not have an existing database schema to work with, so you need to define your relational database schema as you go. At the beginning of the example, the Book class is very simple. It has two fields, title and pages; and an identifier, id, which is an integer. The title is a String object, and pages is an integer. As we go through this example, we will add annotations, fields, and methods to the Book class. The complete source code listing for the Book and Author classes is given at the end of this chapter the source files for the rest are available in the source code download for this chapter on the Apress web site (www.apress.com). Listing 6-3 gives the source code of the Book class, in its unannotated form, as a starting point for the example. Listing 6-3. The Book Class, Unannotated package com.hibernatebook.annotations; public class Book { private String title; private int pages; private int id; // Getters… public int getId() { return id; } public String getTitle() { return title; } public int getPages() { return pages; } // Setters… public void setId(int id) { this.id = id; } public void setTitle(String title) { this.title = title; }
Note: In case you are looking for affordable and reliable webhost to host and run your business application check Vision ftp web hosting services

CHAPTER 6 n MAPPING WITH ANNOTATIONS n MAPPING (Web server info)

Monday, April 16th, 2007

CHAPTER 6 n MAPPING WITH ANNOTATIONS n MAPPING WITH ANNOTATIONS 99 Attribute Name PersistenceContext/ PersistenceContexts PersistenceUnit/ PersistenceUnits PostLoad PostPersist PostRemove PostUpdate PrePersist PreRemove PreUpdate PrimaryKeyJoinColumn/ PrimaryKeyJoinColumns QueryHint SecondaryTable/ SecondaryTables SequenceGenerator SqlResultSetMapping Table T TableGenerator Temporal Transient UniqueConstraint Version Target T, M, and F T, M, and F M M M M M M M T, M, and F Pm T Pk, T, M, and F Pk and T Pk, T, M, and F Pk, T, M, and F M and F M and F Pm M and F Purpose For use with @EntityManager; marks a field or property as representing the EntityManager to be injected by the container. For use with @EntityManager; marks a field or property as representing the EntityManagerFactory to be injected by the container. Marks a method for invocation after performing a load operation on the entity. Marks a method for invocation after performing a persist operation on the entity. Marks a method for invocation after performing a remove operation on the entity. Marks a method for invocation after performing an update operation on the entity. Marks a method for invocation prior to performing a persist operation on the entity. Marks a method for invocation prior to performing a remove operation on the entity. Marks a method for invocation prior to performing an update operation on the entity. Allows the columns joining a secondary table to a primary table to be specified. Allows implementation-specific hints to be provided as a parameter of named queries and named native queries. Allows an entity s basic fields and properties to be persisted to more than one table. Allows a named primary key generator to be defined for use by one or more entities. Allows an entity to be mapped as if it were a named native query (i.e., so that it can be retrieved as a conventional JDBC ResultSet). Allows the default details of an entity s primary table to be overridden. Overrides the default properties of the table used to generate primary keys when the table generation strategy of the generated value annotation is used on the primary key field or property (the field or property marked with the @Id annotation). Specifies the behavior of Date and Calendar fields or properties (if omitted, such fields will be treated as TIMESTAMP values). Allows a field or property to be marked so that it will not be persisted. Enforces a unique constraint at schema generation time as a parameter of @Table. Marks the field or property serving as the optimistic lock value of the entity. Key to the Target column: Pk = package, T = type, M = method, F = field, Pm = parameter
Note: If you are looking for cheap and reliable webhost to host and run your web application check Vision coldfusion web hosting services