3. JPA some common annotations

Source: Internet
Author: User

Common annotations include the following:

①: @Entity, @Table, @Id, @GeneratedValue, @Column, @Basic

②: @Transient used to ignore a property and not persist on the property

③: @Temporal

First, the ① Group notes

    • @Entity the callout is used for the entity class declaration statement, it states that the Java class is an entity class and maps to the specified database table . If you declare an entity class customer, it maps to the Customer table in the database.
    • @Table, when an entity class has a different name than its mapped database table name, you need to use @Table callout description , which is used in parallel with the @Entity callout, before the entity class declaration statement, and can be written in a separate statement row or with a declaration statement. the common option for @Table callouts is name, which indicates the table name of the database .

    • @Id label the attribute that declares an entity class is mapped to the primary key column of the database. This property is typically placed before a property declaration statement and can be used with a declaration statement or on a separate line. @Id Labels can also be placed before the getter method of the property .

    • @GeneratedValue The build policy used to label the primary key , as specified by the Strategy property. By default, JPA automatically chooses a primary key generation strategy that best fits the underlying database: SQL Server corresponds to Identity,mysql for auto increment.

The following policy options are defined in Javax.persistence.GenerationType:

--identity: The way the database ID is grown from the primary key field is not supported by Oracle;

- Auto: JPA automatically chooses the appropriate policy, which is the default option ;

--sequence: The primary key is generated by the sequence, and the sequence name is specified by @SequenceGenerator annotations, which is not supported by MYSQL

Table: A primary key is generated from a table, and the framework borrows the primary key from the table simulation sequence , which makes it easier for the application to migrate the database (the table-generated primary key will be explained in more detail later).

    • @Basic represents a simple property mapping of a field to a database table, and for a getxxxx () method that does not have any callouts, the default is @basic

--fetch: Represents the read policy for this property, with EAGER and lazy two, respectively, for the main support crawl and lazy loading, the default is EAGER.

--optional: Indicates whether the property is allowed to be null, default is True

    • @Column, this annotation description is required when the attribute of an entity differs from the column name of the database table to which it is mapped, which is typically placed before the entity's property declaration statement and can be used with @Id annotations.

--The Name property , which sets the name of the column for the Mapping database table. In addition, the callout contains several other properties, such as unique, nullable, length, and so on.

-- ColumnDefinition Property : represents the actual type of the field in the database .

      A. The ORM framework can automatically determine the type of a field in a database based on the type of the property, but it is still not possible to determine whether the field type in the database is Date,time or timestamp for the date type.

b, in addition, the default mapping type for string is varchar, if you want to map a string type to a BLOB or text field type for a particular database.

--@Column labels can also be placed before the getter method of the property

Second, the ② Group notes

    • Indicates that the property is not a mapping to a field in a database table, which the ORM framework ignores. It acts like a @transient annotation in serialization .
    • If a property is not a field mapping for a database table, it must be marked as @transient; otherwise, the ORM framework defaults to its annotation as @basic

Third, section ③ notes

    • The precision of Date types is not defined in the core Java API (temporal precision). In the database, the data that represents the date type has date, time, and TIMESTAMP three precision (that is, simple dates, times, or both). You can use @temporal annotations to adjust the precision when you make attribute mappings .

The next step is to modify the entity class Customer.java in the 2, JPA HelloWorld, and use the above annotations once to see the actual effect:

1  PackageCom.magicode.jpa.helloworld;2 3 Importjava.util.Date;4 5 ImportJavax.persistence.Column;6 Importjavax.persistence.Entity;7 ImportJavax.persistence.GeneratedValue;8 ImportJavax.persistence.GenerationType;9 Importjavax.persistence.Id;Ten Importjavax.persistence.Table; One Importjavax.persistence.Temporal; A ImportJavax.persistence.TemporalType; - Importjavax.persistence.Transient; -  the /** - * @Entity used to indicate that the class is an entity class - * @Table (name= "T_customer") indicates that the entity class is mapped to the T_customer table of the database -  */ +@Table (name= "T_customer") - @Entity +  Public classCustomer { A  at     PrivateInteger ID; -     PrivateString LastName; -  -     PrivateString Email; -     Private intAge ; -      in     PrivateDate birthday; -      to     PrivateDate createdtime; +  -     /** the * @GeneratedValue (Strategy=generationtype.auto) indicates that the primary key generation policy is AUTO * * @Id indicates the primary key of the entity class $      */Panax Notoginseng@GeneratedValue (strategy=Generationtype.auto) - @Id the      PublicInteger getId () { +         returnID; A     } the  +     /** - * @Column indicates that the LastName attribute is mapped to the Last_Name column of the table $ * You can also specify its length, whether it is null, and other data qualifications $      */ -@Column (name= "last_name", Length=50, nullable=false) -      PublicString Getlastname () { the         returnLastName; -     }Wuyi      the     /** - * Use @Temporal to limit birthday to date type Wu      */ -@Column (name= "Birthday") About @Temporal (temporaltype.date) $      PublicDate Getbirthday () { -         returnbirthday; -     } -  A     /* + * created_time column by @Column ColumnDefinition property the * Mapped to "DATE" type -      */ $@Column (name= "Created_time", columndefinition= "DATE") the      PublicDate Getcreatedtime () { the         returnCreatedtime; the     } the      -     /* in * via the ColumnDefinition property of the @Column the email column the * Mapped to "TEXT" type the      */ About@Column (columndefinition= "TEXT") the      PublicString Getemail () { the         returnemail; the     } +      -     /* the * Tool method, do not need to map to a column of data tableBayi      */ the @Transient the      PublicString GetInfo () { -         return"LastName:" + lastName + "Email:" +email; -     } the  the      Public intGetage () { the         returnAge ; the     } -  the      Public voidsetId (Integer id) { the          This. ID =ID; the     }94  the      Public voidsetlastname (String lastName) { the          This. LastName =LastName; the     }98  About      Public voidsetemail (String email) { -          This. email =email;101     }102 103      Public voidSetage (intAge ) {104          This. Age =Age ; the     }106 107      Public voidsetbirthday (Date birthday) {108          This. Birthday =birthday;109     } the 111      Public voidsetcreatedtime (Date createdtime) { the          This. Createdtime =Createdtime;113     } the      the}

The test in the main method does not change, just add two lines of code while persisting the customer:

// 4, call Entitymanager persist method to complete the persistence process New Customer (); Customer.setage (9); Customer.setemail ("[email protected]") customer.setlastname ("Tom"); // Add 1customer.setbirthday (new  Date ()); // Add 2customer.setcreatedtime (new  Date ()); Em.persist (customer);

  

The following points are summarized for Customer.java:

①, the GetInfo () method, as a tool method, does not need to be mapped to a database. Therefore, @transient is used to indicate that it is ignored when persisted. Otherwise, the JPA default GetInfo method uses the default @basic annotation and persists it to the Info column of the database .

The @temporal (temporaltype.date) annotation is used on the ②, Getbirthday () method to indicate that the birthday corresponding data is stored as date in the persistence process (that is, only "month and Day").

The same effect is reflected in the Getcreatedtime method. Although the method does not use @temporal annotations, @column (name= "Created_time", columndefinition= "DATE")

Indicates "map database column named Created_time", "Data type of corresponding column is date"

③, using @column (columndefinition= "text") on the Getemail () method, indicates that the data type of the e-mail column is "text" (used when storing large text)

④, from ② and ③ can be seen, the value of columndefinition can be directly using the database of the original type name can be

⑤, if you do not specify a mapped column name by using the @column Name property, the default naming method is Getter rule: getxxx corresponds to the name xxx (that is, the first letter becomes lowercase)

The following database is created after running the Main method:

  

Then look at the structure of the table:

  

3. JPA some common annotations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.