Best web design - CHAPTER 6 n MAPPING WITH ANNOTATIONS 103 n
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