Hibernate and JPA annotations

 

1@Entity(name="EntityName")

Must, name is optional, in the corresponding database table in a

 

2@Table(name="",catalog="",schema="")

Alternatively, @Entity usually used in conjunction with, the definition of the class only marked entity, information indicating the entity corresponding to the database table

name: Optional, indicates the name of the table by default, consistent with the table name and the name of the entity, and only in inconsistency only need to specify the table name.

catalog: Optional, expressed Catalog name, default Catalog ( "").

schema: optional, represents Schema name, the default is Schema ( "").

 

3@id

have to

@id defines the primary key attribute is mapped to a database table, a solid can have a primary key attribute is mapped. getXXXX put () before.

 

4@GeneratedValue(strategy=GenerationType,generator="")

Optional (if not written, the primary key need not automatically generated, you need to manually assign)

strategy: represents the primary key generation strategy, there are AUTO, INDENTITY, SEQUENCE, and TABLE 4 species, respectively, so that automatically selects the ORM framework,

The Identity field generating database, the database generated according to Sequence field table, there is an additional table to generate the primary key in accordance with, the default is AUTO

generator: indicates the name of the primary key generator, and this property is typically associated ORM framework, e.g., Hibernate uuid the like can specify the primary key generated.

Example:

 
  1. @Id
  2. @GeneratedValue(strategy = GenerationType.IDENTITY)
  3. @Column(name = "id", nullable = false)
  4. private Long id;

 

5@Basic(fetch=FetchType,optional=true)

Optional

@Basic represents a simple property mapping database table field, marked for no getXXXX () method, that is, the default @Basic

fetch: this attribute indicates the read policy, LAZY and EAGER there are two, namely a front gripping and supporting lazy loading, default EAGER.

optional: indicates that the property is allowed to be null, the default is true

Example:

 
  1. @Lob   // large objects, mapping MySQL types of Long Text
  2. The @basic (FETCH = FetchType.LAZY)  // lazy loading
  3. The @NotEmpty (the Message =  "can not be empty")
  4. @Size(min = 2)
  5. The @Column (= Nullable  to false)  // mapped to fields, values can not be empty
  6. String Content Private; // text of the article content

 

6@Column

Optional

@Column described in detail, the definition of the field in the database table, which the tool according to the database table structure generated JPA annotations very useful.

name: represents the name of the database table in this field, consistent with the default case property names

nullable: indicates that the field is allowed to be null, the default is true

unique: Indicates whether the field is a unique identifier, the default is false

length: indicates the size of the field, the field is valid only for type String

insertable: ORM said in frame insertion operation, whether the field should appear INSETRT statements, the default is true

updateable: ORM framework, said in an update operation, whether the field should appear in the UPDATE statement, the default is true for the field once created can not be changed, the property is useful, such as for birthday field.

columnDefinition: represents the actual type of the field in the database generally ORM framework can attribute type automatically determine the type database field in accordance with, but for Date type does not determine the database field type whether DATE, TIME or TIMESTAMP Further, String's. the default mapping type is VARCHAR, if you want to String types are mapped to BLOB or TEXT field types for a particular database, the property is very useful.

Example:

 
  1. The @NotEmpty (the Message =  "account can not be blank")
  2. @Size(min=3, max=20)
  3. @Column(nullable = false, length = 20, unique = true)
  4. String username Private;  // user account that uniquely identifies when the user logs on

 

7@Transient

Optional

@Transient indicates that the property is not mapped to a field in a database table, ORM framework will ignore the attributes.

If a property is not a field mapping database tables, be sure to mark it as @Transient, otherwise, ORM framework annotated as its default @Basic

Example:

 
  1. The calculated age birth // Properties
  2. @Transient
  3. public int getAge() {
  4.        return getYear(new Date()) - getYear(birth);
  5. }

 

8@ManyToOne(fetch=FetchType,cascade=CascadeType)

Optional

@ManyToOne represents one mapping, the annotation is typically marked foreign key attribute database table

optional: whether to allow the field is null, the property should be determined based on a foreign key constraint database table, the default is true

fetch: fetch strategy represents the default is FetchType.EAGER

cascade: represents the default policy cascade operation, several combinations can be specified as ALL, PERSIST, MERGE, REFRESH, and REMOVE the (end of the text has Detailed), tandem-free operation is the default)

targetEntity: entity type indicates the attribute associated with the specified property is not usually necessary, ORM targetEntity automatically determine the frame type according to the attribute.

Example:

 
  1. The @ManyToOne (Cascade CascadeType.MERGE = {,} CascadeType.REFRESH, = optional  to false) // optional attribute optional = false, indicates author can not be empty
  2. @JoinColumn (name =  "the author_id") // article table provided in the associated field (foreign key)
  3. Author author Private; // belongs author

 

 

9@JoinColumn

Optional

@JoinColumn @Column and the like, the amount of media is not a simple description of the field, and eleven associated field, for example. @ManyToOne described a field.

name: The name of the field because it is associated with a field @JoinColumn described, such as the ManyToOne, determined by the default name associated with the entity.

For example, a user entity attribute Order entity associated User, the user properties of the Order of a foreign key,

The default name for the entity User name + underscore + User entity primary key name

Example:

    See @ManyToOne

 

10@OneToMany(fetch=FetchType,cascade=CascadeType)

Optional

@OneToMany describe one to many association, the property should collective type, and not actually in the database field.

fetch: fetch strategy represents the default is FetchType.LAZY, because multiple objects associated generally not necessary to pre-read from the database into memory

cascade: Indicates cascading operation strategy, is very important for the association OneToMany type, usually when the entity is updated or deleted, its associated entities should also be updated or deleted

For example: Author entities and Article OneToMany the relationship, when the Author entity is deleted, its associated entities Article should be deleted all

Example:

 
  1. @OneToMany(mappedBy = "author",cascade=CascadeType.ALL,fetch=FetchType.LAZY)
  2. Annotated entity classes // mappedBy have to end the relationship is maintained
  3.  // mappedBy = "author" in author is author of properties Article
  4. List Private <Article This article was> articleList; // list of articles

 

11@OneToOne(fetch=FetchType,cascade=CascadeType)

Optional

@OneToOne description associated with a one to one

fetch: fetch strategy represents the default is FetchType.LAZY

cascade: Indicates cascading operation strategy

Example:

 

 
  1. @OneToOne (Cascade = CascadeType.ALL) // People are maintenance side of the relationship
  2.     @JoinTable(name = "people_address",
  3.             joinColumns = @JoinColumn(name="people_id"),
  4.             = inverseJoinColumns  @JoinColumn (name =  "address_id")) // save the relationship by one to one association table
  5.     Address address Private; // address

 

12@ManyToMany

Optional

@ManyToMany describes a many to many association. Two many associations on many association, but ManyToMany description, the middle of the table frame is handled automatically by the ORM

Full name of another entity classes represent many association, such as:: targetEntity package.Book.class

mappedBy: another entity corresponding to many association class represents a set of attribute name

Example:

    User entity represents a user, Book entity represents books, in order to describe the user's favorite books, you can create ManyToMany association between the User and Book

 
  1. @Entity
  2. public class User {
  3.    private List books;
  4.    @ManyToMany(targetEntity=package.Book.class)
  5.    public List getBooks() {
  6.        return books;
  7.    }
  8.    public void setBooks(List books) {
  9.        this.books=books;
  10.    }
  11. }
  12. @Entity
  13. public class Book {
  14.    private List users;
  15.    @ManyToMany(targetEntity=package.Users.class, mappedBy="books")
  16.   public List getUsers() {
  17.        return users;
  18.    }
  19.    public void setUsers(List users) {
  20.        this.users=users;
  21.    }
  22. }

Two interrelated entities must be marked as @ManyToMany attribute, and each attribute specified targetEntity,

It should be noted that there is one and only one entity @ManyToMany comment mappedBy need to specify the property, pointing to a set of attribute names targetEntity

Using the ORM tool automatically generates a table in addition to the User and the Book table, also automatically generates a table User_Book, for implementing many associations

 

13@MappedSuperclass

Optional

@MappedSuperclass JPA annotations can be super class passed to the subclass, the subclass can inherit the superclass JPA annotations

Example:

 
  1. @MappedSuperclass
  2.   public class Employee() {
  3.      ....
  4.   }
  5.   @Entity
  6.  public class Engineer extends Employee {
  7.      .....
  8.   }
  9.   @Entity
  10.   public class Manager extends Employee {
  11.     .....
  12.   }

 

14@Embedded

Optional

@Embedded several fields combined into one class, and a property as a whole Entity.

Including, for example, User id, name, city, street, zip properties.

We hope that city, street, zip property map for the Address object. In this way, User object will have id, name, and address these three attributes.

Address Object must be defined as @Embededable

Example:

 
  1. @Embeddable
  2.   public class Address {city,street,zip}
  3.   @Entity
  4.   public class User {
  5.      @Embedded
  6.      public Address getAddress() {
  7.          ..........
  8.      }
  9.   }

 

Hibernate validation annotations

 

annotation appropriate types Explanation Examples
@Pattern String Regular expression string to verify @attern(regex=”[a-z]{6}”)
@Length String Verification of the length of the string @length(min=3,max=20)
@Email String Verify whether a valid Email address @email
@Range Long Verify whether an integer within the valid range @Range(min=0,max=100)
@ Long Verify must be an integer less than a specified value @Min(value=10)
@Max Long Verify must be an integer not greater than a specified value @Max(value=20)
@Size Collection or array Whether the size of the array or set within the specified range @Size(min=1,max=255)

Each of these notes have a possibility of message attributes, a message is returned to the user after the verification fails, annotations can also be used on a plurality of three properties

 

 

About cascading strategy would add here

  • CascadeType.REMOVE
    Cascade the Remove Operation, cascading deletes.
    When you delete the current entity, and it will be followed by the entity mappings are deleted.
  • CascadeType.MERGE
    Cascade Merge Operation, cascading updates (merge) operation.
    Student when the data was changed, the data in Course updated accordingly.
  • CascadeType.DETACH
    Cascade the detach Operation, cascaded detached / free operations.
    If you want to delete an entity, but it has a foreign key can not be deleted, you will need the permission of the cascade. It will withdraw all foreign key associated.
  • CascadeType.REFRESH
    Cascade Operation Refresh, refresh cascade operation.
    If scenarios there is an order, an order which is associated a lot of merchandise, the order can be a lot of people to operate, then the goods this time A to this order and association were modified at the same time, B also carried out the same operation, but B a first step in saving ratio data, then when a save data, you need to refresh the product information and order information associated with the post, and then save and merchandise orders. (From conscience hurts comment)
  • CascadeType.ALL
    Cascade All the Operations, clear, with all of the above cascade operating authority.

 

 

 

Guess you like

Origin www.cnblogs.com/Jeely/p/11313579.html