Usage and description of Hibernate annotations (ii)

Source: Internet
Author: User

Note mappings must meet two conditions: Hibernate3.2 and Jsee 5.
@Entity class comments, all classes that you want to persist have
@Entity
public class Org implements Java.io.Serializable {
}
@Id PRIMARY Key
@Id
@GeneratedValue
Private String orgId;
Private String OrgName;
@Column (name= "...") this property corresponds to what the field in the table is, not the same as the name
@Table Object and table mappings
@UniqueConstraint UNIQUE Constraint
@Version method and field level, optimistic lock usage, return number and timestamp, number as preferred
@Transient Transient property, indicating that no processing is required
@Basic the most basic comment. There are two properties: Fetch deferred loading, optional allow null
@Enumerated enumeration Types
@Temporal date conversion. Default conversion timestamp
@Lob is usually used in conjunction with @basic to improve access speed.
@Embeddable class level, tables can be embedded in the
@Embedded Method field level, the table is used with the embedded object and @embeddable
@AttributeOverrides Property Overrides
The contents of the @AttributeOverride property override are nested together with the @attributeoverrides
@SecondaryTables Multiple table mappings
@SecondaryTable define auxiliary table mappings and @secondarytables nested together with
@GeneratedValue identifier generation policy, the default auto
Table-to-table relationship mappings
@OneToOne: One-to-one mapping. It consists of five properties:
Targetentity: The target class of the association
Cascade: cascading operation when persisted, no default
Fetch: How to get the object, default eager
Optional: Whether the target object is allowed to be NULL, default allows
Mappedby: Defines a subordinate class in a bidirectional association.
Unidirectional:
@JoinColumn: Define a foreign key (the main table will be one more field, do the foreign key)
@OneToMany: One-to-many mappings; @ManyToOne: multi-pair mapping
One-way pair-more:
@OneToMany (Cascade=cascadetype.all)
@JoinColumn (name= "book_oid")/**book: Table; Oid:book table's primary key; No name is automatically generated by this rule */
One-way many-to-one:
@ManyToOne (Cascade=cascadetype.all)
@JoinColumn (name= "author_oid")
Association table one-to-many:
@OneToMany (Cascade=cascadetype.all)
@JoinTable (joincolumn={@JoinColumn (name= "book_object_oid")},inversejoincolumns={@JoinColumn (name= "Auther_ Object_oid ")})
Bi-directional one-to-many or multiple-pair:
No more tables are needed, just use Mappedby: Using the one side, the value is the one party class name that represents the subordinate class of many.
@Entity
Java code
@Entity
public class Org implements Java.io.Serializable {


Fields
@Id
@GeneratedValue
Private String orgId;
Private String OrgName;
@OneToMany (mappedby = "org")
Private list<department> departments;

Constructors
...
Property accessors
...
}

@Entity public  class Org  implements Java.io.Serializable {        //Fields       @Id   @GeneratedValue       Private String orgId;       Private String OrgName;       @OneToMany (mappedby = "org")       private list<department> departments;        Constructors ...      Property accessors ...  }


@Entity
Public class Department implements java.io.Serializable {
// fields
@Id
@GeneratedValue
private String ID;
private String name;
@ManyToOne (Fetch=fetchtype.eager)
@JoinColumn (name= "Org_orgid")
private org org;
@OneToMany (mappedby = "department")
private list<employee> employees;
//Constructors
Public list<employee> GetEmployees () {
return employees;
}
Public void Setemployees (list<employee> employees) {
this.employees = employees;
}
Public Org getorg () {
return org;
}
Public void setorg (org org) {
this.org = org;
}
/** Default constructor * /
             .
             .
             .
}
Java Code
@Entity
Public class Employee implements java.io.Serializable {
   
   
// fields
@Id
@GeneratedValue
private String employeeId;
private String EmployeeName;
private String PassWord;
private Integer age;
private Integer sex;
@ManyToOne (Fetch=fetchtype.eager)
@JoinColumn (name= "department_id")
private Department Department;
   
         
Public Department getdepartment () {
return department;
     }    
   
Public void Setdepartment (Department Department) {
this.department = Department;
     }    
   
/** Default constructor * /
     ...    
//Property accessors
     ...    
}   

@Entity public  class Employee  implements Java.io.Serializable {        //Fields       @Id   @GeneratedValue       private String employeeId;       Private String EmployeeName;       Private String PassWord;       Private Integer age;       Private Integer sex;       @ManyToOne (Fetch=fetchtype.eager)       @JoinColumn (name= "department_id")       Private Department department;               Public Department getdepartment () {    return Department;   }     public void Setdepartment (Department Department) {    this.department = Department;   }     /** default constructor */      ...      Property accessors ...  }


bidirectional Many-to-many: @ManyToMany. One-way many-to-many here is not to repeat (not much practical significance)
This is relatively simple, look at the code to understand:
@Entity
Public class book implements java.io.Serializable {
@Id
private int id;
private String name;
private float money;
@ManyToMany (cascade = cascadetype.all)
private list<author> authors;
Public list<author> GetAuthors () {
return authors;
}
Public void Setauthors (list<author> authors) {
this.authors = authors;
}
         ...
}
@Entity
Public class Author implements java.io.Serializable {
@Id
private int id;
private String name;
private int age;
@ManyToMany (mappedby= "authors")
private list<book> books;
Public list<book> Getbooks () {
return books;
}
Public void Setbooks (List<book> books) {
this.books = books;
}
         ...
}
Note-based Hibernate primary key settings: @Id.
So what is the rule of generating it? is stipulated by the @generatedvalue.
let's start by looking at how it's defined:
Java Code
@Target ({Method,field})
@Retention (RUNTIME)
Public @interface generatedvalue{
generationtype strategy () default AUTO;
String Generator () default "";
     }   

@Target ({Method,field})   @Retention (RUNTIME) public   @interface generatedvalue{    generationtype Strategy () default AUTO;    String generator () Default "";   }



Java code
public enum generationtype{
TABLE,
SEQUENCE,
IDENTITY,
AUTO
}

public enum generationtype{    TABLE,    SEQUENCE,    IDENTITY,    AUTO   }


Now we see that it provides 4 build strategies:
Table: Use a specific database table to hold the sequence of identifiers.
SEQUENCE: Generates a serialization identifier.
IDENTITY: The identifier has a database auto-generated (mainly auto-growth type)
Auto: Identifier generation work is handled automatically by hibernate. Actual project development is not recommended.
Note: Using @generatedvalue is not working correctly when the primary key is int and the database is not auto-growing.
We can also use the following method to specify our primary key values:

Java code
@GeneratedValue (generator = "c-assigned")
@GenericGenerator (name = "c-assigned", strategy = "assigned")
Private String employeeId;

@GeneratedValue (generator = "c-assigned")   @GenericGenerator (name = "c-assigned", strategy = "assigned")       Private String employeeId;


or do not define @generatedvalue directly, only the @id effect is the same.

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.