Hibernate annotation notes

Source: Internet
Author: User
(1)
Introduction:
Over the past few years, Hibernate has been evolving and has almost become a de facto standard for Java Database persistence. It is very powerful, flexible, and has excellent performance. In this article, we will learn how to use Java 5 annotations to simplify hibernate Code And make the coding process of the persistent layer easier.
Traditionally, Hibernate configuration depends on external XML files: Database ing is defined as a group of XML ing files and loaded at startup.
In several recently released hibernate versions, a more clever new method based on Java 5 annotations has emerged. With the new hibernate annotation library, you can allocate all the old ing files at a time-everything will be defined according to your ideas-annotations are directly embedded into your Java class, it also provides a powerful and flexible way to declare persistent ing. After hibernate annotations are used, you do not need to define the *. HBM. xml file corresponding to the persistence class, which is directly written into the persistence class as annotations. Hibernate annotation uses the annotation of ejb jpa. Therefore, when installing and configuring the hibernate annotation environment below, you need to import the EJB package. Many online documents are related to JPA hibernate annotation. (2)
Install hibernate Annotation
Step 1,
Environment and jar package:
To use hibernate annotation, you must have at least hibernate 3.2 and Java 5. You can download the hibernate 3.2 and hibernate annotation libraries from the hibernate site. In addition to the standard hibernate jar and dependencies, you also need the hibernate annotations. jar file (hibernate-annotations.jar), Java persistence API (LIB/ejb3-persistence.jar ). Add hibernate3.2.jar, hibernate-annotations-3.3.0.jar, hibernate-commons-annotations.jar, and ejb3-persistence.jar. In this way, you can use the annotation of hibernate.

If you are using Maven, you only need to add the corresponding dependency to the POM file, as shown below:
...
<Dependency>
<Groupid> org. hibernate </groupid>
<Artifactid> hibernate </artifactid>
<Version> 3.2.1.ga </version>
</Dependency>
<Dependency>
<Groupid> org. hibernate </groupid>
<Artifactid> hibernate-annotations </artifactid>
<Version> 3.2.0.ga </version>
</Dependency>
<Dependency>
<Groupid> javax. Persistence </groupid>
<Artifactid> persistence-API </artifactid>
<Version> 1.0 </version>
</Dependency> Step 2,
Obtain the hibernate session factory. Although there is no need to worry about modification, this work is different from using hibernate annotations. You need to use the annotationconfiguration class to create a session Factory:
Sessionfactory = new annotationconfiguration (). buildsessionfactory ();
Step 3,
Although the <mapping> element is usually used to declare the persistence class, you still need to declare the persistence class in the hibernate configuration file (usually hibernate. cfg. XML:
<! Doctype hibernate-configuration public
"-// Hibernate/hibernate configuration DTD 3.0 // en"
Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd>
<Hibernate-configuration>
<Session-factory>
<Mapping class = "com. onjava. modelplanes. domain. planetype"/>
<Mapping class = "com. onjava. modelplanes. domain. modelplane"/>
</Session-factory>
</Hibernate-configuration>
Many recent Java projects have used lightweight application frameworks, such as spring. If you are using the Spring framework, you can use the annotationsessionfactorybean class to easily create a annotation-based hibernate session factory, as shown below:
<! -- Hibernate session factory -->
<Bean id = "sessionfactory"
Class = "org. springframework. Orm. hibernate3.annotation. annotationsessionfactorybean">
<Property name = "datasource">
<Ref bean = "datasource"/>
</Property>
<Property name = "hibernateproperties">
<Props>
<Prop key = "hibernate. dialect"> org. hibernate. dialect. derbydialect </prop>
<Prop key = "hibernate. hbm2ddl. Auto"> Create </prop>
...
</Props>
</Property>
<Property name = "annotatedclasses">
<List>
<Value> com. onjava. modelplanes. domain. planetype </value>
<Value> com. onjava. modelplanes. domain. modelplane </value>
...
</List>
</Property>
</Bean> (3)
Use of the hibernate annotation Tag: [1]
1. The persistent classes with annotations are also common pojo. They are only common pojo with persistent annotations. 2. In fact, you can maintain the persistence of fields (comments are written on member variables) or attributes (comments are written on the getter method. 3. Common hibernate annotation labels are as follows: @ Entity -- Annotation declares that the class is a persistent class. Declare a JavaBean class as a database table ing Class of an object, so it is best to implement serialization. by default, all class attributes are persistent fields mapped to the data table. if another attribute is added to the class instead of mapped to the database, the following transient is used for annotation. @ Table (Name = "promotion_info") -- Persistence ing table (table name = "promotion_info ). @ table is a Class-level annotation. It is defined under @ entity as the object bean ing table, the directory and schema name. By default, it is the class name of the object bean without the package name. @ ID -- Annotation can indicate which attribute is the unique identifier in the class (that is, equivalent to the primary key of the data table ).
@ Generatedvalue -- Defines the automatic growth primary key generation policy.
@ Transient -- These fields and attributes are ignored and do not need to be persisted to the database. yes. In the current persistent class, some attributes are not used to map to a data table, but to other business logic needs. In this case, these attributes must be annotated with transient. otherwise, the system will fail to map the corresponding fields of the data table.
@ Temporal (Temporaltype. timestamp) -- declare the time format
@ Enumerated -- Declare Enumeration
@ Version -- Declare support for Optimistic Locking
@ Onetoone -- One-to-one association between object beans can be established.
@ Onetoworkflow -- One-to-multiple associations between object beans can be established.
@ Manytoone -- Multiple-to-one association between object beans can be established.
@ Manytoyun -- Multiple-to-multiple associations between object beans can be established.
@ Formula -- An SQL expression. This attribute is read-only and is not generated by the database (sum, average, and Max can be used)
@ Orderby -- List 1.2
Hibernate can automatically generate primary keys. Hibernate/ebj 3 annotations can also provide rich support for Automatic Generation of primary keys, allowing various policies.
The generation rule is set by @ generatedvalue. Here, @ ID and @ generatedvalue are both standard usage of JPA. JPA provides four standard usage methods, which are defined by @ generatedvalue Source code Obviously.
JPA provides four standard usage methods: Table, sequence, identity, and auto.
Table: Use a specific database table to save the primary key.
Sequence: generate a primary key based on the sequence of the underlying database, provided that the database supports the sequence.
Identity: The primary key is automatically generated by the database (mainly the auto-growth type)
Auto: primary key from Program Control. If the primary key generation policy is not specified when the primary key is specified, the default value is auto.
@ ID is equivalent to @ ID
@ Generatedvalue (Strategy = generationtype. auto) Identity: Use the auto-increment fields of SQL Server and MySQL. This method cannot be placed in Oracle. Oracle does not support auto-increment fields, set sequence (MySQL and SQL Server are commonly used ). Oracle is about to adopt sequence. At the same time, other policies such as UUID and native can also be used. (related usage and online query) [2] The first persistent class @ entity
@ Table (name = "t_model_plane ")
Public class modelplane implements serializable {
@ ID
@ Column (name = "plane_id ")
@ Generatedvalue (Strategy = generationtype. Auto) // annotation in attributes
/*
For Oracle to use their sequence, the settings are as follows:
@ Generatedvalue (Strategy = generationtype. Auto, generator = "promotion_seq ")
@ Sequencegenerator (name = "promotion_seq", sequencename = "promotion_seq ") In addition: For fields in the data table that are automatically increased, set the field to auto_increment.
*/
Private long ID;

Private string name; // The annotation is written on the getter method. See.

// Date-java. SQL. date
// time-java. SQL. time
// timestamp-java. SQL. timestamp
@ temporal (temporaltype. timestamp)
@ column (name = "start_time")
private date starttime;

// Show 0 hide 1
Public static Enum displaytype {Show, hide}
@ Enumerated (value = enumtype. ordinal) // ordinal number
Private displaytype = displaytype. display;

// 1. The fields and table names in the SQL statement should correspond to the database, rather than the fields in the class,
// If there is a parameter such as La. ID = ID, this = ID is the attribute in the class.
// 2. aliases must be used for operation fields
@ Formula (select count (LA. ID) from largess la)
Private int count;

// annotation in method
@ column (name = "plane_id", length = 80, nullable = true) // more detailed definition
Public String getname () {
return name;
}< br> Public void setname (string name) {
This. name = Name;
}< br> Other setter, Getter omitted ......
}this content will be mapped to the following table:
Create Table t_model_plane
(
plane_id long,
plane_name varchar
other fields are omitted...
)

By default, Hibernate maps persistent classes to tables and fields with matched names. For example, in the following example, if no annotation is required, it is mapped to the following table:
Create Table modelplane
(
Id long,
Other fields of name varchar are omitted...
) [3]
One-to-multiple annotation: 1. In one-to-multiple annotation, the "one" side is used:
@ Onetoworkflow --> mappedby: Association attribute of "multiple" parties (Under prosecution)
"Multi:
@ Manytoone --> @ joincolumn, a foreign key field defined by "multiple" parties. for example, if the data table defines the foreign key as follows: foreign key (classid) References classes (ID) then: @ joincolumn (name = "classid") 2. in two-way Association, only one end exists as the owner end: the subject is responsible for maintaining the connection column (I .e. updating ), for slave tables that do not need to maintain such a relationship, the mappedny attribute is declared. The value of mappedby points to the association attribute of another subject. In this example, the value of mappedby is classes. Additional instructions: Mappedby is equivalent to the previous inverse = "true ".
The side of inverse = false (side actually refers to the class element where inverse = false is located) has the responsibility to maintain the relationship, while the side of inverse = true does not need to maintain the relationship. 3. Cascade and fetch usage instructions: Cascade Cascadetype. persist (cascade new)
Cascadetype. Remove (cascade delete)
Cascadetype. Refresh (cascade refresh)
Select one or more cascadetype. Merge (cascade update.
Cascadetype. All Fetch attributes: Gets the association, that is, whether to use delayed loading.
Lazy (default value) uses delayed loading. When querying data, the data of the associated object is not queried together. However, when you access an associated object (for example, getstudnets (), the corresponding query operation is triggered to obtain the associated object data.
Eager: obtains the data of the associated object directly when querying data. Package onetoworkflow;
Import java. util. Set;
Import javax. Persistence .*;
/*
Note: Import javax. Persistence .*;
Related Classes for non-import org. hibernate: Import org. hibernate. Annotations. entity;
*/
@ Entity
@ Table (name = "classes ")
Public class classes implements serializable {
@ ID
@ Generatedvalue (Strategy = generationtype. Auto)
Private int ID;
Private string name;

@ Onetomany (cascade = cascadetype. All, mappedby = "classes ")
Private set <student> students;
// Getter, setter omitted
}

Package onetoworkflow;
Import javax. Persistence .*;
@ Entity
@ Table (name = "student ")
Public class student implements serializable {
@ ID
@ Generatedvalue (Strategy = generationtype. Auto)
Private int Sid;

Private string sname;

// If multiple cascade instances exist, they can be: {cascadetype. persist, cascadetype. Merge}
@ Manytoone (cascade = {cascadetype. All })
@ Joincolumn (name = "classid") // the attribute of the corresponding foreign key in the student class: classid
Private classes;
// Getter, setter omitted
}

Public class testonetomany {
/*
Create Table student (-- to define a foreign key !!!!!!!
'Sid 'Double not null auto_increment,
'Classid' double null,
'Sname' varchar (255) not null,
Primary Key (SID ),
Index par_ind (classid ),
Foreign key (classid) References classes (ID) on Delete cascade on update Cascade
) Engine = InnoDB
*/
Public static void main (string [] ARGs) throws sqlexception
{
Try
{
Sessionfactory Sf = new annotationconfiguration (). Configure (). buildsessionfactory ();
Session session = SF. opensession ();
Transaction Tx = session. begintransaction ();/* Because mappedby is defined in classes, the classes class is not responsible for maintaining cascading relationships. that is, student is the maintainer. so, 1. assign the clsses data to student, that is, use the setclasses () method of student to bundle the class data; 2. during data insertion/update session. save ()/session. during Update (), student is the last operation. */
Classes classes = new classes ();
Classes. setname ("access ");

Student ST1 = new student ();
St1.setsname ("Jason ");
St1.setclasses (classes );
Session. Save (ST1 );

Student st2 = new student ();
St2.setsname ("hwj ");
St2.setclasses (classes );
Session. Save (st2 );
TX. Commit ();/* The output is as follows: Hibernate: insert into classes (name) values (?)
Hibernate: insert into student (classid, sname) values (?, ?)
Hibernate: insert into student (classid, sname) values (?, ?) * // * Because one end maintains the relationship and the other end does not maintain the relationship, we must avoid using classes that do not maintain the relationship in the application to establish the relationship, because the established relationship will not be stored in the database. When the code above is reversed, the foreign key value of student is blank during insertion. The following is: * // student ST1 = new student ();
// St1.setsname ("Jason ");
// Session. Save (ST1 );
//
// Student st2 = new student ();
// St2.setsname ("hwj ");
// Session. Save (st2 );
//
// Set <student> students = new hashset <student> ();
// Students. Add (ST1 );
// Students. Add (st2 );
//
// Classes = new classes ();
// Classes. setname ("access ");
// Classes. setstudents (students );
// Session. Save (classes );/* The output is as follows:
Hibernate: insert into student (classid, sname) values (?, ?)
Hibernate: insert into student (classid, sname) values (?, ?) Hibernate: insert into classes (name) values (?) */
}
Catch (hibernateexception E)
{
E. printstacktrace ();
}
}
}

[4]
many-to-many Annotations: both parties use @ manyto. in many-to-many annotations. it is set as in One-to-multiple annotations, and mappedby should also be set. the main prosecution, unlike one-to-many annotations, uses @ joincolumn instead of @ jointable. as follows: @ jointable (name = "j_student_course", joincolumns ={@ joincolumn (name = "Sid")}, inversejoincolumns ={@ joincolumn (name = "CID ")}) among them, as mentioned above, mappedby is equivalent to inverse = "true ". therefore, the field defined in inversejoincolumns in @ jointable is the primary key of the class where mappedby is located.
the field defined by joincolumns is the primary key of the current class. @ entity
@ table (name = "jcourse")
public class jcourse {
@ ID
@ generatedvalue (Strategy = generationtype. auto)
private int CID;
private string cname;
@ manytomany (cascade = {cascadetype. persist, cascadetype. merge}, fetch = fetchtype. lazy, mappedby = "courses")
private set students;
// setter, Getter omitted ....
}

@ Entity
@ Table (name = "jstudent ")
Public class jstudent {
@ ID
@ Generatedvalue (Strategy = generationtype. Auto)
Private int Sid;

Private string sname;

@ Manytomany (cascade = {cascadetype. persist, cascadetype. Merge}, fetch = fetchtype. Eager)
// The ID in inversejoincolumns is the corresponding ID of the course attribute.
@ Jointable (name = "j_student_course", joincolumns ={@ joincolumn (name = "Sid")}, inversejoincolumns ={@ joincolumn (name = "CID ")})
Private set <jcourse> courses;
// Setter, Getter omitted ....
}

Public class test {
Public static void main (string [] ARGs ){
Try
{
Sessionfactory Sf = new annotationconfiguration (). Configure (). buildsessionfactory ();
Session session = SF. opensession ();
Transaction Tx = session. begintransaction ();

Jcourse course = new jcourse ();
Course. setcname ("Jason-English ");
Session. Save (course); // save them first.

Jcourse course2 = new jcourse ();
Course2.setcname ("Herry-English ");
Session. Save (course2 );

Set <jcourse> courses = new hashset <jcourse> ();
Courses. Add (course );
Courses. Add (course2 );

Jstudent student = new jstudent ();
Student. setsname ("Jason ");
Student. setcourses (courses );

Session. Save (student); // use a class not defined by mapby (studet) to act as the master (control cascading relationships). The same applies to one-to-many and multiple-to-one operations.
// You can try to reverse.
TX. Commit ();
}
Catch (hibernateexception E)
{
E. printstacktrace ();
}
}
}

Attachment download:
Annocation-jar01.rar
Annocation-jar02.rar

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.