Hibernate4 annotation Method (full)

Source: Internet
Author: User
Tags class definition db2 generator inheritance uuid
1. Class-level annotations

@Entity Mapping entity classes

@Table map number of database tables

@Entity (name= "TableName")-Must be, annotations declare a class as an entity bean.

Property:

name-Optional, corresponding to a table in the database. If the table name is the same as the entity class name, you can omit it.

@Table (name= "", catalog= "", Schema= "")-optional, usually used in conjunction with @entity, can only be labeled at the class definition of the entity, representing the information for the database table of the entity.

Property:

Name-optional, indicates the name of the table, by default, the table name and entity name are the same, only need to specify the table name in case of inconsistency

Catalog-optional, which represents the catalog name, which defaults to catalog ("").

Schema-optional, representing the schema name, which defaults to schema (""). 2. Attribute level annotations

To generate a primary key @Id map

@Version Defining optimistic Locks

@Column the columns of the mapping table

@Transient Defining Transient Properties

2.1 Notes related to the primary key

@Id-a property that is mapped to the primary key of a database table must be defined, and an entity can have only one attribute mapped to the primary key, before Getxxxx ().

@GeneratedValue (strategy=generationtype,generator= "")-optional, which defines the primary key generation strategy.

Property:

Strategy-Represents the primary key generation policy, with the following values:

Generationtype.auto-Automatically select based on the underlying database (default), or autogrow if the database supports auto-grow types.

Generationtype.indentity-based on the identity field of the database, supports the identity type primary key for DB2, MySQL, MS, SQL Server, Sybase, and Hyperanoicsql databases.

Generationtype.sequence-use SEQUENCE to determine the value of the primary key, suitable for Oracle, DB2 and other support SEQUENCE database, generally combined with @sequencegenerator.

(Oracle does not have auto-grow type, only with sequence)

Generationtype.table-uses the specified table to determine the primary key value, combined with @tablegenerator.

Such as:

@Id

@TableGenerator (name= "Tab_cat_gen", allocationsize=1)

@GeneratedValue (strategy=generationtype.table)

Generator-Represents the name of the primary key generator, which is usually related to the ORM framework, for example:

Hibernate can specify how to generate primary keys such as UUID

@SequenceGenerator-the annotation declares a database sequence.

Property:
Name-represents the table primary key generation policy name, which is referenced in the "Gernerator" value set in @generatedvalue.
Sequencename-Indicates the name of the database sequence used to generate the policy.
InitialValue-Represents the primary key initial value, which defaults to 0.
Allocationsize-Each time the primary key value increases in size, for example, set to 1, it indicates that a new record is automatically added 1 after each creation, and the default is 50.

Example:

@Id

@GeneratedValues (strategy=strategytype.sequence)

public int getpk () {

return PK;

}

When Hibernate's access type is field, the annotation sounds on the field;

When the access type is property, a comment declaration is made on the getter method.

2.2 Notes related to non-primary keys

@Version-@version annotations can be used in entity beans to add support for optimistic locking

@Basic-the access policy used to declare properties:

@Basic (Fetch=fetchtype.eager) Instant access (default Access Policy)

@Basic (Fetch=fetchtype.lazy) delayed acquisition

@Temporal-Used to define the time precision mapped to the database:

@Temporal (temporaltype=date) Date

@Temporal (Temporaltype=time) time

@Temporal (Temporaltype=timestamp) both

@Column-You can map a property to a column, use that annotation to override the default value, @Column describe the detailed definition of the field in the database table, which is useful for tools that generate database table structures based on JPA annotations.

Property:

Name-optional, which represents the names of the fields in the database table, and the default case property names are the same

Nullable-optional, indicates whether the field is allowed to be null, default is True

Unique-optional, indicates whether the field is a unique identity, false by default

Length-optional, indicates the size of the field, only valid for a field of type String, and the default value is 255.

Insertable-optional, indicating whether the field should appear in the INSETRT statement when the ORM Framework performs an insert operation, which is true by default

Updateable-optional, indicating whether the field should appear in the UPDATE statement when the ORM framework performs an update operation, which is true by default. This property is useful for fields that cannot be changed once created, such as for birthday fields.

ColumnDefinition-optional, which represents the actual type of the field in the database. Usually 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. In addition, the default mapping type for string is varchar, which is useful if you want to map a string type to a blob or text field type of a particular database.

Example:

@Column (name= "BIRTH", nullable= "false", columndefinition= "DATE")

Public String Getbithday () {

return birthday;

}

@Transient-optional, which indicates that the property is not a mapping to a field in a database table, the ORM framework ignores the property, and 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

Example:

Calculates the age property based on birth

@Transient

public int getage () {

Return GetYear (New Date ())-getYear (birth);

} 2.3 Default value for no annotation properties

If the property is a single type, it is mapped to @basic,

Otherwise, if the property corresponds to a type that defines the @embeddable annotation, the mapping is @embedded,

Otherwise, if the property corresponds to a type that implements serializable, the property is mapped to @basic and the serialized version of the object is saved in a column.

Otherwise, if the property is of type Java.sql.Clob or JAVA.SQL.BLOB, it acts as @lob and maps to the appropriate lobtype:

3. Mapping Inheritance Relationships

@Inheritance annotations to define the selected policy. This annotation requires the use of 4 on the topmost entity class for each class hierarchy . Mapping Entity Bean Association Relationship 4.1 Some definitions of association mappings

One-to-many: a party has a collection attribute, contains multiple parties, and the parties do not have a reference to a party. User---> Email

One-way many-to-one: multiple parties have a reference, one side does not have a multi-party reference. Paper Category---> Category

Bi-directional one-to-many: there are multiple references on both sides, convenient to query. Class---> Students

Bidirectional many-to-one: Both sides have a multi-reference, convenient query.

One-way many-to-many: an intermediate table is required to maintain two entity tables. Forum---> Articles

One-way: data is unique, and database data is single. Ship---> Sailors

Primary key is the same as one to the other: Use the same primary key, omitting foreign key associations. Customer---> Address

One-way: who manages which side of the relationship is written.

Bidirectional: Generally managed by multiple parties.

@OneToMany (mappedby= "opposite Party")//reverse configuration, the other side management. 4.2 Some common properties of association mappings

Common attributes for @OneToOne, @OneToMany, @ManyToOne, Manytomany:

Fetch-Configures the mode of loading. Value is

Fetch.eager-Load in time, many to one default is Fetch.eager

Fetch.lazy-Lazy load, one-to-many default is Fetch.lazy

Cascade-Sets the cascading method, with the following values:

Cascadetype.persist-Save

Cascadetype.remove-Delete

Cascadetype.merge-Modify

Cascadetype.refresh-Refresh

Cascadetype.all-All

Targetentity-Configure collection property types, such as: @OneToMany (Targetentity=book.class)

@JoinColumn-optional, used to describe an associated field.

@JoinColumn similar to @column, a medium is not a simple field, but an associated field, such as a field that describes a @manytoone.

Property:

Name-the names of the fields, because @joincolumn describes an associated field, such as Manytoone, the default name is determined by its associated entity.

For example, the entity order has a user attribute to associate the entity user, and the order's user property is a foreign key.

Its default name is entity user name + underscore + entity user primary key name 4.3 one-to-one association

@OneToOne – Represents a one-to-one mapping

1. The primary table Class A corresponds to the primary key value from table Class B.
Main Table: @OneToOne (cascade= cascadetype.all)
@PrimaryKeyJoinColumn
Public B Getb () {

Returnb;

}
From table: None

2. The main Table A has a type B from the Table property

Main Table: @OneToOne (cascade = Cascadetype.all)
@JoinColumn (name= "primary table foreign Key")//The Foreign key field in the database is specified here.
PUBLICB Getb () {

return b;

}

From table: None

3. There is one in main Table A from the table property is type B, and at the same time, from table B there is a primary table property is a type a
Main Table: @OneToOne (cascade = Cascadetype.all)
@JoinColumn (name= "primary table foreign Key")//The Foreign key field in the database is specified here.
PUBLICB Getb () {

return b;

}
From table: @OneToOne (mappedby= "from table properties in the Main Table class")
Public Main Table class get Main Table class () {

Return Main Table Object

}
Note: The @JoinColumn is optional. The default value is from the table variable name + "_" + the primary key from the table (note that this Riga is the primary key.) Instead of the primary key). 4.4 Many-to-one correlation

@ManyToOne-Represents a many-to-one mapping, which is typically a foreign key to a database table.

1. One-way many-to-one: multiple parties have a reference, one side does not have a multi-party reference.

In multiple

@ManyToOne (Targetentity=xxxx.class)//Specify associated objects

@JoinColumn (name= "")//Specify the resulting foreign key field name

2. Bidirectional many-to-one: the configuration is the same as two-way pair.

Example:

Order orders and user users are a manytoone relationship

Defined in the Order class

@ManyToOne ()

@JoinColumn (name= "USER")

Public User GetUser () {

return user;

} 4.5 One-to-many associations

@OneToMany-Describes a one-to-many association, which should be a collection type, with no actual fields in the database.

1. One-way-to-many: one party has a collection attribute, contains multiple parties, and the parties do not have a reference to a party.

@OneToMany use the Join table as a one-to-many association by default

When you add @joincolumn (name= "xxx_id"), the Foreign Key association is used instead of the join table.

2. Bidirectional one-to-many

1) in multiple

@ManyToOne

@JoinColumn (name= "own database foreign key column name")

2) on one side

@OneToMany (mappedby= "Multi-Port Association property name")

@JoinColumn (name= "Each other's database foreign key column name") 4.6 Many-to-many associations

@ManyToMany-optional, describes a many-to-many association.

Property:

Targetentity-The full name of another entity class that represents a many-to-many association, for example: package. Book.class

Mappedby-In the bidirectional correlation, the maintenance right of the relationship is flipped.

1. One-way many-to-many associations:

Add @manytomany annotations to the main control side.

2. Bidirectional many-to-many associations:

The attributes that are related to the two entities must be marked as @manytomany and specify the Targetentity property with each other. @manytomany annotations that have and only one entity need to specify the Mappedby property, which points to the Targetentity collection property name.

[From:blog_935ebb670101dnre.html] @Entity, register on the class header, declare a class as an entity bean (that is, a persisted Pojo class). @Table, registered on the class header, the annotation declares the table specified by the Entity bean mapping. @Id is used to register the main property, @GeneratedValue the build policy used to register the main property, @Column used to register the attribute, @Version to register an optimistic lock, @Transient to register the property. The above @id, @GeneratedValue, @Column, @Version, can be used to register properties, either written on the properties of the Java class, or can be registered on the property corresponding getter. The @Transient is registered on an extra property or extra getter, but must correspond to the above @column. @Column the fields corresponding to the identity attribute, example: @Column (name= "UserName")
@Column (
Name= "ColumnName"; (1)
Booleanunique () Defaultfalse; (2)
Booleannullable () Defaulttrue; (3)
Booleaninsertable () Defaulttrue; (4)
Booleanupdatable () Defaulttrue; (5)
Stringcolumndefinition () Default ""; (6)
Stringtable () Default ""; (7)
int length () default255; (8)
Intprecision () default 0; Decimalprecision (9)
int scale () default 0; Decimalscale (1) name optional, column name (default is property name) (2) Unique optional, whether to set a unique constraint on this column (default value False) (3) Nullable optional, set the value of the column can be empty (default Value false) (4) Insertable optional, whether the column is a column in the resulting INSERT statement (default value TRUE) (5) Updatable optional, whether the column is a column in the generated UPDATE statement (default value TRUE) (6) ColumnDefinition Optional: Overwrite the SQL DDL fragment for this particular column (this may result in a failure to migrate between different databases) (7) Table optional, define the corresponding table (default is the primary table) (8) Length optional, column length (default value 255) (8) Precisi On optional, the column decimal precision (decimal precision) (default 0) scale is optional, if the column decimal value range is available, this setting (the default value of 0) @Id, identifies that this property is the only recognized value of the entity class.Note: This annotation can only label a primary key consisting of a single column, such as Tbl_grade, a union primary key with two fields identified by other annotations. Recall *.hbm.xml: "UUID" > "Assigned"/> @Id, just to identify that the property is a primary key, but does not indicate its build policy, as in the previous example, the assigned is the build policy specified by the programmer. If you only write @Id, you use assigned to generate a little, such as: @Id
@Column
private int uuid;
If you want to use Oracle-supported sequence to take a primary key, you must specify the build policy through @generatedvalue, and the @sequencegenerator specifies how to use sequence.
@Id
@Column
@GeneratedValue (
Strategy = generationtype.sequence,//using SEQUENCE to generate a primary key
Generator = "Generator"//references the following build policy named Gernator
)
@SequenceGenerator (
Name = "Generator",//define a build policy named generator
Allocationsize = 1,//each sequence plus 1
Name= "Seq_a"//refer to sequence named seq_a
)
private int uuid;
@Version identifies the Version @Transient this property is used to map an optimistic lock this property does not have to be persisted @Embeddable an embedded component (Embeddedcomponent) can be defined in the identity entity on the head of a small object. Component classes must define @embeddable annotations at the class level. @Embedded "on the property header of a large object" refers to a small object defined. An embedded component (Embeddedcomponent) can be defined @Embeddable the "Head of small objects" identity entity. Component classes must define @embeddable annotations at the class level. Note: If this small object is a composite primary key, be sure to implement the serializable interface. This is not an annotation decision, but the primary key for hibernate needs to implement the serializable interface. @EmbeddedId "on the property header of a large object" refers to the defined small object as the primary key. Note: You do not need to use @id annotations again.

@Id
	@GeneratedValue (strategy = Generationtype.auto)//PRIMARY key default policy (primary key policy determined by the underlying database) public
	Integer getId () {
		return ID;
	}
	public void SetId (Integer id) {
		this.id = ID;
	}
	
	@ManyToMany (
			//targetentity Configuration collection Property type
			Targetentity=cn.com.goevent.omms.bean.companyinfo.class,
			// Fetch load mode, lazy load
			fetch=fetchtype.lazy)
	//association table
	@JoinTable (
			name= "Exhibition_user",//association table name ( Exhibition_user Maintenance data table for many-to-many relationships
			joincolumns={@JoinColumn (name= "exhibition_id")},//maintenance end foreign keys 
			

Configuration of XML Primary 1 "tbl_product":

From 1 "tbl_product_info":
Product "refers to its own Java property name"
Configuration of AnnotationsMain 1 "tbl_product":
@OneToOne (Cascade=cascadetype.all)
@PrimaryKeyJoinColumn
Private Productinfomodel info;
From 1 "tbl_product_info":
@Id
@Column
@GeneratedValue (generator= "copy" reference Generation Policy "")
@GenericGenerator (name= "copy" definition Generation Strategy "", strategy= "foreign" write dead, use foreign policy "", parameters= @Parameter (name= "Property", Value= "Product" refers to its own Java attribute "")
private int uuid;
@OneToOne (mappedby= "info" references each other's Java Properties "")
Private ProductModel product;
the standard 1:m Configuration of XML1 "tbl_parent":
Multiple "Tbl_child":
Configuration of Annotations1 "tbl_parent":
@OneToMany
@JoinColumn (name= "Puuid" for each other's database foreign key column name "")
Private Set children = new HashSet ();
Multiple "Tbl_child":
@ManyToOne
@JoinColumn (name= "Puuid" own database foreign key column name "")
Private Parentmodel parent;


Main 1 "tbl_product": "cascade=" All "/> from 1" tbl_product_info ": true" Write Dead ""/>

Configuration of Annotations

Main 1 "tbl_product":
@OneToOne (cascade=cascadetype.all,mappedby= "product" for each other's Java class Property name "")
Private Productinfomodel info;
From 1 "tbl_product_info":
@OneToOne
@JoinColumn (name= "Puuid" own database foreign key column name "")
Private ProductModel product;



Configuration of XML

1 "tbl_parent":
Class= "Cn.javass.model.d.childmodel" Each other's Java class name ""/>
configuration of Annotations 1 "tbl_parent": @OneToMany (mappedby= "parent" of each other's Java class Property name "") Private Set children = new HashSet (); Multiple "Tbl_child": @ManyToOne @JoinTable (name= "Tbl_parent_child" junction Table "", joincolumns= @JoinColumn (name= "cuuid" join tables represent their own data Library field name ""), inversejoincolumns= @JoinColumn (name= "puuid" Join table represents each other's database field name "")) private Parentmodel parent;



Configuration of XML

1 "tbl_product":
Configuration of Annotations

1 "tbl_product":
@ManyToOne
@JoinTable (
Name= "tbl_product_relation" junction Table "",
Joincolumns= @JoinColumn (The name= "suuid" Join table represents its own column name ""),
inversejoincolumns= @JoinColumn (name= "cuuid" Join table represents the other party's column name "", Unique=true "Write Dead")
)
Private Coursemodel course;

Error One
Error message: javax.persistence.Table.indexes ([Ljavax/persistence/index
Cause: Hibernate4.3 does not support @table (name= "tablename")
Solution: Use @entity (name= "tablename") instead of @table (name= "tablename")
Error two
Error message: Javax.persistence.JoinColumn.foreignKey () Ljavax/persistence/foreignkey
Cause: Hibernate4.3 cannot use @joincolumn when many-to-one mappings
Solution: Write only @manytoone error three
Error message: Javax.persistence.OneToMany.orphanRemoval () Z
Cause: Java EE, EJB, or JUnit jar packages conflict with Hibernate-jpa-2.0-api-1.0.0.final.jar
Solution: See if there are any of the above jar packages, if present, remove them

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.