Archive for April, 2007

118 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER (Web hosting comparison)

Wednesday, April 25th, 2007

118 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS Listing 6-16. Mapping a Many-to-One Relationship from the PublisherEntity to the Book Entity @ManyToOne @JoinColumn(name = “publisher_id”) public Publisher getPublisher() { return publisher; } The @ManyToOne annotation takes a similar set of attributes to @OneToMany. The following list describes the attributes, all of which are optional. cascade indicates the appropriate cascade policy for operations on the association; it defaults to none. fetch indicates the fetch strategy to use; it defaults to LAZY. optional indicates whether the value can be null; it defaults to true. targetEntity indicates the entity that stores the primary key this is normally inferred from the type of the field or property (Publisherin the preceding example). We have also supplied the optional @JoinColumnattribute to name the foreign key column required by the association something other than the default (publisher) this is not necessary, but it illustrates the use of the annotation. When a unidirectional one-to-many association is to be formed, it is possible to express the relationship using a link table. This is achieved by adding the @JoinTable annotation as shown in Listing 6-17.2 Listing 6-17. A Simple Unidirectional One-to-Many Association with a Join Table @OneToMany(cascade = ALL) @JoinTable public Set getBooks() { return books; } The @JoinTable annotation provides attributes that allow various aspects of the link table to be controlled. These attributes are as follows: name is the name of the join table to be used to represent the association. catalog is the name of the catalog containing the join table. schema is the name of the schema containing the join table. joinColumns is an array of @JoinColumn attributes representing the primary key of the entity at the one end of the association. inverseJoinColumns is an array of @JoinColumn attributes representing the primary key of the entity at the many end of the association. 2. When a join table is being used, the foreign key relationship is maintained within the join table itself it is therefore not appropriate to combine the mappedBy attribute of the @OneToMany annotation with the use of an @JoinTable annotation.
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check Vision mysql hosting services

CHAPTER 6 n (Web design company) MAPPING WITH ANNOTATIONS 117 n

Wednesday, April 25th, 2007

CHAPTER 6 n MAPPING WITH ANNOTATIONS 117 n MAPPING WITH ANNOTATIONS 117 COLLECTION ORDERING EJB 3 does not provide for maintaining the ordering of an ordered collection such as an array or a list see the Ordering Collections with @IndexColumn section of the chapter for discussion on how the @IndexColumn annotation can be used in a non-portable way to remedy this deficiency. The collection, however, can be specified in terms of the fields of the associated entity at retrieval time by means of the @OrderBy annotation. For example, if we were to retrieve a list ordered by the books names in ascend- ing order, we could annotate a suitable method. The following code snippet specifies a retrieval order for an ordered collection. @OneToMany(cascade = ALL, mappedBy = “publisher” @OrderBy(”name ASC”) public List getBooks() { return books } The value of the @OrderBy annotation is an ordered list of the field names to sort by, each one option- ally appended with ASC (for ascending order, as in the preceding code) or DESC (for descending order). If neither ASC nor DESC is appended to one of the field names, the order will default to ascending. @OrderBy can be applied to any collection-valued association. The mappedBy attribute is mandatory on a bidirectional association and optional (being implicit) on a unidirectional association. cascade is optional, taking a member of the javax.persistence.CascadeType enumeration and dictating the cascade behavior of the mapped entity. targetEntity is optional, as it can usually be deduced from the type of the field or property, as in Listing 6-15, where the property represents a Set of Book entities, making the target entity implicitly Book. However, if necessary (if generics are not being used, for example), the class of the target entity can be provided here. fetch is optional, allowing lazy or eager fetching to be specified as a member of the javax.persistence.FetchType enumeration. Listing 6-15. Mapping a One-to-Many Relationship from the Book Entity to the Publisher Entity @OneToMany(cascade = ALL,mappedBy = “publisher”) public Set getBooks() { return books; } The many-to-one end of this relationship is expressed in similar terms to the one-tomany end, as shown in Listing 6-16.
Note: If you are looking for cheap webhost to host and run your apache application check Vision apache web hosting services

116 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER (Web hosting script)

Tuesday, April 24th, 2007

116 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS CASCADING OPERATIONS When an association between two entities is established (for example, a one-to-one association between Human and Pet), it is common to want certain persistence operations on one entity to also be applied to the entity that it is linked to. Take, for example, the following code: Human dave = new Human(”dave”); Pet cat = new PetCat(”Tibbles”); dave.setPet(cat); session.save(dave); In the last line, highlighted in bold, we are likely to want to save the Pet object associated with the Human object. In a one-to-one relationship, we usually expect all operations on the owning entity to be propagated through that is, to be cascaded to the dependent entity. In other associations this is not true, and even in a one-to-one relationship we may have special reasons for wanting to spare the dependent entity from delete operations (perhaps for auditing reasons). We are therefore able to specify the types of operations that should be cascaded through an association to another entity using the cascade annotation, which takes an array of members of the CascadeType enumeration. The members correspond with the names of the key methods of the EntityManager class used for EJB 3 persistence, and have the following rough correspondence with operations on entities: ALL requires all operations to be cascaded to dependent entities. This is the same as including MERGE, PERSIST, REFRESH, and REMOVE. MERGE cascades updates to the entity s state in the database (i.e., UPDATE …). PERSIST cascades the initial storing of the entity s state in the database (i.e., INSERT…). REFRESH cascades the updating of the entity s state from the database (i.e., SELECT …). REMOVE cascades deletion of the entity from the database (i.e., DELETE . . .). If no cascade type is specified, no operations will be cascaded through the association. In the light of these options, the appropriate annotation for the relationship between a publisher and its address would be as follows: @OneToOne(cascade=CascadeType.ALL) public Address getAddress() { return this.address; } The simplest way to maintain a many-to-one relationship between two entities is by managing the foreign key of the entity at the one end of the one-to-many relationship as a column in the many entity s table. The @OneToMany annotation can be applied to a field or property value for a collection or an array representing the mapped many end of the association.
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision servlet hosting services

CHAPTER 6 n MAPPING WITH ANNOTATIONS (Web design rates) 115 n

Monday, April 23rd, 2007

CHAPTER 6 n MAPPING WITH ANNOTATIONS 115 n MAPPING WITH ANNOTATIONS 115 Neither Hibernate nor the EJB 3 standard supports mapping an embedded object across more than one table. In practice, if you want this sort of persistence for your embedded entity, you will usually be better off making it a first-class entity (i.e., not embedded) with its own @Entity marker and @Idannotations, and then mapping it via a conventional one-to-one association, as explained in the next section. Mapping a Conventional One-to-One Association There is nothing intrinsically wrong with mapping a one-to-one association between two entities where one is not a component of (i.e., embedded into) the other. The relationship is often somewhat suspect, however. You should give some thought to using the embedded technique described previously before using the @OneToOne annotation. Assuming that you are resolute on declaring the association in this way (perhaps because you anticipate converting it to a one-to-many or many-to-one relationship in the foreseeable future), applying the annotation is quite simple all of the attributes are optional. Listing 6-14 shows how simply a relationship like this might be declared. Listing 6-14. Declaring a Simple One-to-One Relationship @OneToOne public Address getAddress() { return this.address; } The @OneToOne annotation permits the following optional attributes to be specified: targetEntity can be set to the class of an entity storing the association. If left unset, the appropriate type will be inferred from the field type, or the return type of the property s getter. cascade can be set to any of the members of the javax.persistence.CascadeType enumeration. It defaults to none being set. See the Cascading Operations sidebar for a discussion of these values. fetch can be set to the EAGER or LAZY members of FetchType. optional indicates whether the value being mapped can be null. mappedBy indicates that a bidirectional one-to-one relationship is owned by the named entity.1 The owning entity contains the primary key of the subordinate entity. Mapping a Many-to-One or One-to-Many Association A many-to-one association and a one-to-many association are the same association seen from the perspective of the owning and subordinate entities, respectively. 1. An association is bidirectional if each entity maintains a property or field representing its end of the same relationship. For example, if our Address class maintained a reference to the Publisher located there, and the Publisher class maintained a reference to its Address, then the association would be bidirectional.
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services

114 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER (Web hosting isp)

Monday, April 23rd, 2007

114 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS Mapping an Embedded (Component) One-to-One Association When all the fields of one entity are maintained within the same table as another, the enclosed entity is referred to in Hibernate as a component. The EJB 3 standard refers to such an entity as being embedded. The @Embedded and @Embeddable attributes are used to manage this relationship. In this book s database example, we associate an AuthorAddressclass with an Authorclass in this way. The AuthorAddress class is marked with the @Embeddableannotation. An embeddable entity must be composed entirely of basic fields and attributes. An embeddable entity can only use the @Basic, @Column, @Lob, @Temporal, and @Enumerated annotations. It cannot maintain its own primary key with the Id tag because its primary key is the primary key of the enclosing entity. The @Embeddable annotation itself is purely a marker annotation, and takes no additional attributes, as demonstrated in Listing 6-11. Typically, the fields and properties of the embeddable entity need no further markup. Listing 6-11. Marking an Entity for Embedding Within Other Entities @Embeddable public class AuthorAddress { … } The enclosing entity then marks appropriate fields or getters in entities, making use of the embeddable class with the @Embedded annotation, as shown in Listing 6-12. Listing 6-12. Marking an Embedded Property @Embedded public AuthorAddress getAddress() { return this.address; } The @Embedded annotation draws its column information from the embedded type, but permits the overriding of a specific column or columns with the @AttributeOverrideand @AttributeOverrides tags (the latter to enclose an array of the former if multiple columns are being overridden). For example, Listing 6-13 shows how to override the default column names of the addressand country attributes of AuthorAddress with columns named ADDR and NATION. Listing 6-13. Overriding Default Attributes of an Embedded Property @Embedded @AttributeOverrides({ @AttributeOverride(name=”address”,column=@Column(name=”ADDR”)), @AttributeOverride(name=”country”,column=@Column(name=”NATION”)) }) public AuthorAddress getAddress() { return this.address; }
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision personal web hosting services

CHAPTER 6 (Best web design) n MAPPING WITH ANNOTATIONS 113 n

Monday, April 23rd, 2007

CHAPTER 6 n MAPPING WITH ANNOTATIONS 113 n MAPPING WITH ANNOTATIONS 113 nullable permits the column to be marked NOT NULL when the schema is generated. The default is that fields should be permitted to be null; however, it is common to override this when a field is, or ought to be, mandatory. unique permits the column to be marked as containing only unique values. This defaults to false, but commonly would be set for a value that might not be a primary key but would still cause problems if duplicated (such as username). We have marked up the title field of our Book entity using the @Column entity to show how three of these attributes would be applied: @Column(name=”working_title”,length=200,nullable=false) public String getTitle() { return title; } The remaining attributes, less commonly used, are as follows: table is used when the owning entity has been mapped across one or more secondary tables. By default, the value is assumed to be drawn from the primary table, but the name of one of the secondary tables can be substituted here (see the @SecondaryTable annotation example earlier in this chapter). insertable defaults to true, but if set to false, the annotated field will be omitted from insert statements generated by Hibernate (i.e., it won t be persisted). updatable defaults to true, but if set to false, the annotated field will be omitted from update statements generated by Hibernate (i.e., it won t be altered once it has been persisted). columnDefinition can be set to an appropriate DDL fragment to be used when generating the column in the database. This can only be used during schema generation from the annotated entity, and should be avoided if possible, since it is likely to reduce the portability of your application between database dialects. precision permits the precision of decimal numeric columns to be specified for schema generation, and will be ignored when a non-decimal value is persisted. The value given represents the number of digits in the number (usually requiring a minimum length of n+1, where n is the scale). scale permits the scale of decimal numeric columns to be specified for schema generation and will be ignored where a non-decimal value is persisted. The value given represents the number of places after the decimal point. Modeling Entity Relationships Naturally, annotations also allow you to model associations between entities. EJB 3 supports one-to-one, one-to-many, many-to-one, and many-to-many associations. Each of these has its corresponding annotation. We discussed the various ways in which these mappings can be established in the tables in Chapter 5. In this section, we will show how the various mappings are requested using the annotations.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision shared web hosting services

112 CHAPTER 6 n (Yahoo web hosting) MAPPING WITH ANNOTATIONS CHAPTER

Sunday, April 22nd, 2007

112 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS optional. The first attribute is named optional and takes a boolean. Defaulting to true, this can be set to falseto provide a hint to schema generation that the associated column should be created NOT NULL. The second is named fetchand takes a member of the enumeration FetchType. This is EAGER by default, but can be set to LAZY to permit loading on access of the value. The use of lazy loading is unlikely to be valuable, except when large serializable objects have been mapped as basic types (rather than given entity mappings of their own) and retrieval time may become significant. While the (default) EAGER value must be honored, the LAZY flag is considered to be a hint, and can be ignored by the persistence engine. The @Basic attribute is usually omitted, with the @Column attribute being used where the @Basic annotation s optional attribute might otherwise be used to provide the NOT NULL behavior. Omitting Persistence with @Transient Some fields may be used at run time only, and should be discarded from objects as they are persisted into the database. The EJB 3 specification provides the @Transient annotation for these transient fields. The @Transient annotation does not have any attributes you just add it to the instance variable or the getter method as appropriate for the entity bean s property access strategy. For our example, we contrive to add a Date field named publicationDate, which will not be stored in the database to our Book class. We mark this field transient thus: @Transient public Date getPublicationDate() { return publicationDate; } Because we are using a property access strategy for our Book class, we must put the @Transient annotation on the getter method. Mapping Properties and Fields with @Column The @Column annotation is used to specify the details of the column to which a field or property will be mapped. Some of the details are schema related, and therefore apply only if the schema is generated from the annotated files. Others apply and are enforced at run time by Hibernate (or the EJB 3 persistence engine). It is optional, with an appropriate set of default behaviors, but is often useful when overriding default behavior, or when you need to fit your object model into a preexisting schema. It is more commonly used than the similar @Basic annotation, with the following attributes commonly being overridden: name permits the name of the column to be explicitly specified by default, this would be the name of the property. However, it is often necessary to override the default behavior when it would otherwise result in an SQL keyword being used as the column name (e.g., user). length permits the size of the column used to map a value (particularly a String value) to be explicitly defined. The column size defaults to 255, which might otherwise result in truncated String data, for example.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

CHAPTER 6 n MAPPING WITH ANNOTATIONS 111 n (Christian web host)

Sunday, April 22nd, 2007

CHAPTER 6 n MAPPING WITH ANNOTATIONS 111 n MAPPING WITH ANNOTATIONS 111 Listing 6-10. An Example of a Field Access Entity Mapped Across Two Tables package com.hibernatebook.annotations; import javax.persistence.*; @Entity @Table(name=”CUSTOMER”) @SecondaryTable(name=”CUSTOMER_DETAILS”) public class Customer { @Id public int id; public String name; @Column(table=”CUSTOMER_DETAILS”) public String address; } Columns in the primary or secondary tables can be marked as having unique values within their tables by adding one or more appropriate @UniqueConstraint annotations to @Table or @SecondaryTable s uniqueConstraints attribute. For example, to mark the name field in the preceding declaration as being unique, use the following: @Entity @Table( name=”CUSTOMER”, uniqueConstraints={@UniqueConstraint(columnNames=”name”)} ) @SecondaryTable(name=”CUSTOMER_DETAILS”) public class Customer { … } Persisting Basic Types with @Basic By default, properties and instance variables in your POJO are persistent Hibernate will store their values for you. The simplest mappings are therefore for the basic types. These include primitives, primitive wrappers, arrays of primitives or wrappers, enumerations, and any types that implement Serializable but are not themselves mapped entities. These are all mapped implicitly no annotation is needed. By default, such fields are mapped to a single column, and eager fetching is used to retrieve them (i.e., when the entity is retrieved from the database, all the basic fields and properties are retrieved). Also, when the field or property is not a primitive, it can be stored and retrieved as a null value. This default behavior can be overridden by applying the @Basic annotation to the appropriate class member. This annotation takes two optional attributes, and is itself entirely
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services

110 CHAPTER (Cheapest web hosting) 6 n MAPPING WITH ANNOTATIONS CHAPTER

Saturday, April 21st, 2007

110 CHAPTER 6 n MAPPING WITH ANNOTATIONS CHAPTER 6 n MAPPING WITH ANNOTATIONS public static class AccountPk { // … } } Regardless of which of these approaches we take to declare our compound primary key, the table that will be used to represent it will require the same set of columns. Listing 6-9 shows the DDL that will be generated from any of Listings 6-6, 6-7, or 6-8. Listing 6-9. The DDL Generated from the Annotated Account Class (Regardless of the Approach Used) create table Account ( code varchar(255) not null, number integer not null, description varchar(255), primary key (code, number) ); Database Table Mapping with @Table and @SecondaryTable The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. If you omit the annotation, Hibernate will default to using the class name for the table name, so you only need to provide this annotation if you want to override that behavior. The @Table annotation provides four attributes, allowing you to override the name of the table, its catalog, and its schema, and enforce unique constraints on columns in the table. Typically, you would only provide a substitute table name thus: @Table(name=” ORDER_HISTORY”). The unique constraints will be applied if the database schema is generated from the annotated classes, and will supplement any column-specific constraints (see discussions of @Column and @JoinColumn later in this chapter). They are not otherwise enforced. The @SecondaryTable annotation provides a way to model an entity bean that is persisted across several different database tables. Here, in addition to providing an @Tableannotation for the primary database table, your entity bean can have an @SecondaryTable annotation, or an @SecondaryTables annotation in turn containing zero or more @SecondaryTable annotations. The @SecondaryTable annotation takes the same basic attributes as the @Table annotation, with the addition of the join attribute. The join attribute defines the join column for the primary database table. It accepts an array of javax.persistence.PrimaryKeyJoinColumnobjects. If you omit the joinattribute, then it will be assumed that the tables are joined on identically named primary key columns. When an attribute in the entity is drawn from the secondary table, it must be marked with the @Columnannotation, with a table attribute identifying the appropriate table. Listing 6-10 shows how a property of the Customer entity could be drawn from a second table mapped in this way.
Note: If you are looking for cheap webhost to host and run your apache application check Vision apache web hosting services

Web hosting e commerce - CHAPTER 6 n MAPPING WITH ANNOTATIONS 109 n

Saturday, April 21st, 2007

CHAPTER 6 n MAPPING WITH ANNOTATIONS 109 n MAPPING WITH ANNOTATIONS 109 Listing 6-8. Using the @IdClass and @Id Annotations to Map a Compound Primary Key package com.hibernatebook.annotations; import javax.persistence.*; @Entity @IdClass(Account.AccountPk.class) public class Account { private String description; private String code; private Integer number; public Account(String description) { this.description = description; } protected Account() { } @Id public String getCode() { return this.code; } @Id public Integer getNumber() { return this.number; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public void setNumber(Integer number) { this.number = number; } public void setCode(String code) { this.code = code; }
Note: In case you are looking for affordable and reliable webhost to host and run your business application check Vision php5 hosting services