Shangxue Tang Hibernate Notes

Quote

New Project 1
2 learning to build user-library-hibernate, and add the appropriate jar package
a project right-build path-configure build path-add library
b select the user-library, in which the new library, lives life to hibernate
c in the library needs to add hibernate jar package
hibernate3.3.2
/ Hibernate3.jar
/ Lib / required directory of all packages 6
Sl4j-nop jar
3 introduces the JDBC driver package mysql
4 built in the MYSQL database and corresponding table student (id, name, age)
Create hibernate configuration file hibernate.cfg.xml 5
Reference document COPY, modify the corresponding database connection
Establishment of student class 6
7 to establish the corresponding mapping file reference documentation Student.hbm.xml
8 will be added to the mapping file in hibernate-cfg.xml

Built environment and configure the log display DDL statements
slf implementation: slf4j nodep, log4j, jdk logging api, apache common-log.
slf4j.nop.jar is slf-api.jar the corresponding interface's interface to the slf log4j implementation, the user library in hibernate, the realization of the slf slf4j-nop-1.5.8.jar removed, added log4j implementation of log4j-1.2.15.jar, and then add a slf-api and log4j converter slf4j-log4j12-1.5.8.jar.
The slf log4j interface into the interface. Finally add a log4j configuration file log4j.properties

HIBERNATE export database tables using built
/ / Read configuration file hibernate.cfg.xml
Configuration cfg = new AnnotationConfiguration (). Configure (); (annotated using AnnotationConfiguration), configure () you can manually specify the configuration file name.
Configuration cfg = new Configuration (), will be the default file to read hibernate.properties
/ / Create object schemaExport
import org.hibernate.tool.hbm2ddl.SchemaExport;
SchemaExport export = new SchemaExport (cfg);
/ / Create the database tables
export.create (true, true);

Object mapping (using Annotation annotation method)
Table 1 Construction
Create table teacher (id int primary key, name varchar (20), title varchar (20));
2 Create teacher class, and the annotation @
import javax.persistence.Entity;
import javax.persistence.Id;
Adding comments in the bean
@ Entity, @ Id (added to the getId () above)
3 In the hibernate jar to add the appropriate annotation package
hibernate-annotations.jar
/ Lib directory, add the appropriate package ejb3-persistence.jar, hibernate-commons-annotations.jar
Note: annotation document did not mention the hibernate-annotations.jar package
4 reference documentation to establish the corresponding annotation annotation
5 In the hibernate.cfg.xml to create maps
<mapping"com.xx.xx"/>
Example 6
/ / AnnotationConfiguration;
Configuration cfg = new AnnotationConfiguration ();
SessionFactory sf = cfg.configure (). BuildSessionFactory ();
Session session = sf.openSession ();
session.beginTransaction ();
session.save (t); / /
session.getTransaction (). commit ();
session.close ();
sf.close ();

Object mapping (using the configuration file method)
1 in the corresponding class in the establishment of the corresponding configuration file.
For example, the corresponding Student class profile Student.hbm.xml
<hibernate-mapping package="com.model">
<class name="Student" table=" Student">
<id name="id" column="id"> </ id>
<property name="name" column="name" />
<property name="age" column="age" />
</ Class>
</ Hibernate-mapping>
2 In the hibernate.cfg.xml file Student.hbm.xml added to the map
<! - Create the corresponding configuration file associated with the corresponding database tables ->
<mapping resource="com/model/Student.hbm.xml"/> attention to writing the package name
Example 3
/ / Read configuration file hibernate.cfg.xml
Configuration cfg = new Configuration (). Configure ();
/ / Create SessionFactory
SessionFactory sf = cfg.configure (). BuildSessionFactory ();
/ / Create session
Session session = sf.openSession ();
session.beginTransaction ();
session.save (s);
session.getTransaction (). commit ();
session.close ();
sf.close ();

hibernate.cfg.xml configuration
hibernate.hbm2ddl.auto value of the property: validate | update | create | create-drop
In sessionfactory created, automatically checks the data structure, or the database schema (tables) of the DDL to export to the database, use the create-drop, in the closed sessionfactory explicitly, it will drop out of the database schema.
loading hibernate validate, verify that create the database table structure
create each load hibernate, re-create the database table structure
hibernate create-drop loads created when the exit is to remove the table structure
update add hibernate automatically update the database structure

Table names and class names in different situations, on the table configuration
1 in the comment
import javax.persistence.Table;
@ Table (name = "TableName")
2 in the XML file
<hibernate-mapping package="com.model">
<class name="Teacher" table="Teacher"> configuration attribute table corresponding to the appropriate table name
<id name="id" column="id"> </ id>
...
</ Class>
</ Hibernate-mapping>

The same field names and attribute names, the default is for the annotation, if any notes are not write it, the equivalent of adding the annotation @ Basic
Entity bean and all non-transient non-static properties can be persistent, unless you be annotated as @ Transient. All annotation attribute is not defined in the above is equivalent to adding the @ Basic annotation. Through the @ Basic annotation can be declared property acquisition strategies (fetch strategy):
For XML documents without writing a column.

Field names and attribute names are not the same time
Annotation: @ column (name = "column_name") with the corresponding getXXX () method
XML: column attributes

The field does not need persistence
import javax.persistence.Transient;
@ Transient means that this property is transparent, not to persistent storage when not put into your account

Mapping the date and time types, specify the time accuracy
Annotation:
import javax.persistence.Temporal;
@ Temporal (TemporalType.TIME)

XML: Specifies the type
<class name="Teacher" table="Teacher">
<id name="id" column="id"> </ id>
<property name="name" type="time" /> type = time or date
</ Class>

Enumeration type of conversion
@ Enumerated (EnumType.STRING)

Recommended location of field mapping methods written in gexXXX

Hibernate mapping type
Java Hibernate mapping type size and type of the standard range of SQL types
integer or int int or java.lang.Integer INTEGER 4 bytes
long long Long BIGINT 8 bytes
short short Short SMALLINT 2 bytes
byte byte byte Byte TINYINT 1
float float Float FLOAT 4 bytes
double double Double DOUBLE 8 bytes
big_decimal java.math.BigDecimal NUMERIC NUMERIC (8,2) 8 Bit
character char Character String CHAR (1) fixed-length character
variable-length string string String VARCHAR
boolean boolean boolean Boolean BIT
yes_no boolean Boolean CHAR (1) (YN) boolean
true_false boolean Boolean CHAR (1) (TF) boolean
2, Java Hibernate time and date the type of Java type mapping mapping types described in the standard SQL type
date util.Date or sql.Date DATE YYYY-MM-DD
time Date Time TIME HH: MM: SS
timestamp Date Timestamp TIMESTAMP YYYYMMDDHHMMSS
calendar calendar TIMESTAMP YYYYMMDDHHMMSS
calendar_date calendar DATE YYYY-MM-DD
3, Java Hibernate mapping types of large object type mapping Java types types types of standard MySQL Oracle SQL type type
binary byte [] VARBINARY (or BLOB) BLOB BLOB
text String CLOB TEXT CLOB
serializable Serializable interface to any implementation class VARBINARY (or BLOB) BLOB BLOB
clob java.sql.Clob CLOB TEXT CLOB
blob java.sql.Blob BLOB BLOB BLOB
In the program or by Hibernate to save java.sql.Clob java.sql.Blob instance, must include two steps:
1, the first transaction in a database kept an empty Blob or Clob instance.
2 and then lock the record, update, save the Blob or Clob above example, the binary data or text data written to Blob or Clob instance

Hibernate SQL dialect (hibernate.dialect)
RDBMS dialect
DB2 org.hibernate.dialect.DB2Dialect
DB2 AS/400 org.hibernate.dialect.DB2400Dialect
DB2 OS390 org.hibernate.dialect.DB2390Dialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
MySQL org.hibernate.dialect.MySQLDialect
MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect
MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle 9i/10g org.hibernate.dialect.Oracle9Dialect
Sybase org.hibernate.dialect.SybaseDialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect
Microsoft SQL Server org.hibernate.dialect.SQLServerDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Informix org.hibernate.dialect.InformixDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Ingres org.hibernate.dialect.IngresDialect
Progress org.hibernate.dialect.ProgressDialect
Mckoi SQL org.hibernate.dialect.MckoiDialect
Interbase org.hibernate.dialect.InterbaseDialect
Pointbase org.hibernate.dialect.PointbaseDialect
FrontBase org.hibernate.dialect.FrontbaseDialect
Firebird org.hibernate.dialect.FirebirdDialect

ID generation strategy <generator>
1.XML <generator> configure optional child element is a Java class name, used for the persistent instance of the class to generate unique identifiers. If the generator instance need to configure or initialize the parameters to pass with <param> elements.
<id name="id" type="long" column="cat_id">
<generator>
<param name="table"> uid_table </ param>
<param name="column"> next_hi_value_column </ param>
</ Generator>
</ Id>
All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface; some applications may choose to provide their own specific implementation. Of course, Hibernate provides many built-in implementation. Here are some built-in shortcut name generator:
 increment used to long, short or int type to generate a unique identity. Only when no other process to insert the same data in a table can be used. Do not use the cluster.
 identity of DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL built-in identification field support. The returned identifier is long, short or int type.
 sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi used in sequence (sequence), and in the use of Interbase generator (generator). The returned identifier is long, short or int type.
 hilo uses a hi / lo algorithm to efficiently generate long, short or int type identifier. Given a table and column (by default is hibernate_unique_key and next_hi) as a source of high value. Hi / lo algorithm generates identifiers that only in a particular database is unique.
 seqhilo uses a hi / lo algorithm to efficiently generate long, short or int type of identifier, given a database sequence (sequence) of the name.
 uuid's with a 128-bit UUID algorithm to generate identifiers of type string, which is only a network (using the IP address). UUID is encoded as a 32-bit 16 hex digit string.
 guid in MS SQL Server and MySQL database-generated GUID in the string.
 native ability to choose based on the underlying database, identity, sequence or hilo one. The default is in the mysql auto_increment, SQLSERVER is identity.
 assigned lets the application to save () before the allocation of an identifier for the object. This is <generator> element does not specify the default generation strategy.
 select the database trigger by selecting some unique key of the row and return to the main key to assign a primary key.
 foreign associated with another object identifier. <one-to-one> Usually used together.
 sequence-identity of a particular sequence generation strategy, the use of database sequence to generate the actual value, but will it JDBC3 the getGeneratedKeys together, making the implementation of the insert statement generated when the value is returned. So far only for JDK 1.4 for Oracle 10g driver support this strategy. Note that because Oracle driver, a bug, the insert statement of the comments are closed. (Original: Note comments on these insert statements are disabled due to a bug in the Oracle drivers.)
2 annotation id generation strategy is configured using the @ Id annotation can be an attribute in an entity bean is defined as the identifier (identifier). The property can be set through the application itself can also be generated by Hiberante (recommended).
@ GeneratedValue annotation can be defined using the identifier generation strategy: There are four strategies  AUTO - default. Can be a identity column type or sequence type or table type, depending on the underlying database .. for MYSQL, is auto_increment, for Oracle is a hibernate-sequence.
 TABLE - save the id value using the table (to know)
 IDENTITY - identity column
 SEQUENCE - @ SequenceGenerator
@ GeneratedValue (strategy = GenerationType.XXXX)
XXXX value for the Type.SEQUENCE | TABLE | AUTO | IDENTITY different databases corresponding to different generation strategies.
Example 1
Entity class notes
@ Entity
Note the primary key for
@ Id
@ GeneratedValue
The default value is @ GeneratedValue (strategy = GenerationType.AUTO)
Example 2
Use SequenceGenerator
@ Entity
@ SequenceGenerator (
name = "teacher_SEQUENCE", sequenceName = "teacher_SEQUENCE_DB")
is a user-defined name generator name generator, sequenceName sequence is generated to the database object names.
After the entity annotation, you can write on the id corresponding annotation
@ Id
@ GeneratedValue (
strategy = GenerationType.IDENTITY, generator = "teacher_SEQUENCE")
Example 3
Table Generator (understanding), this approach will also generate a table.
Entity class notes
@ Entity
@ Javax.persistence.TableGenerator (/ / to know, is more suitable for cross-platform and cross database.
name = "TEACHER_GEN", / / name generator generator
table = "GENERATOR_TABLE", / / generate table name
pkColumnName = "pk_key", / / generate the table field name
valueColumnName = "pk_value", / / generate the field value table
pkColumnValue = "teacher", / / pk_key field value
allocationSize = 1 / / increment variable
)
Note the primary key
@ Id
@ GeneratedValue (strategy = GenerationType.TABLE, generator = "TEACHER_GEN")

 joint primary key generation strategy commonly used in this way, such as a class Student (id, name, age), in order to produce a composite key, the id and name separated.
Student (pk, age) StudentPk (id, name)
StudentPk serialized class must implement the interface implements java.io.Serializable.
StudentPk class must override the boolean equals (), int hasCode () method
@ Override
public boolean equals (Object o) {
if (o instanceof StudentPk) {
StudentPk pk = (StudentPk) o;
if (this.id == pk.getId () & & this.name.equals (pk.getName ())) {
return true;
}
}
return false;
}

@ Override
public int hashCode () {
return this.name.hashCode ();
}
The primary key generation strategy XML configuration
<composite-id name="pk">
<key-property name="id"> </ key-property>
<key-property name="name"> </ key-property>
</ Composite-id>
The primary key generation strategy annotation configuration composite primary key defined in three ways:
 (less) to the component class annotated as @ Embeddable, and component property annotated @ Id.
Solid Model Teacher (teacherPK, age) TeacherPk (id, name)
In TeacherPk (id, name) in the annotation @ Embeddable class
In the Teacher (teacherPK, age) in the component properties teacherPK @ Id annotation
 properties of the component annotation is @ EmbeddedId.
Solid Model Teacher (teacherPK, age) TeacherPk (id, name)
Only in the Teacher (teacherPK, age) in the component properties teacherPK annotation @ EmbeddedId
 (recommended) to class annotated as @ IdClass, and all of the entity primary key attributes are annotated as @ Id.
Solid Model Teacher (id, name, age) TeacherPk (id, name)
In the Teacher (id, name, age) in the Class Notes @ IdClass (value = "TeacherPk.Class"), the primary key attributes id, name can be on the @ Id annotation. When IdClass () is only one property in default written IdClass (TeacherPk.Class). That Teacher inside the component properties id, name, is the class together just TeacherPk.

Three states of the object

The difference between three states:
There is no ID, ID in the database have not, there in memory (session cache)
Three states
Transient: an object in memory, no ID, no cache
Persistent: in memory, in cache, the database ID in
Detached: memory in the cache are not, the database has ID

Core Interface Development Introduction
Configuration
1 AnnotationConfiguration
Configuration information management 2
3 used to generate the SessionFactory: buildSessionFactory ()
4 can configure () method in hibernate configuration file specified

SchemaExport
Control can be generated in the program built predicative name.
Located in the package import org.hibernate.tool.hbm2ddl.SchemaExport;
create (boolean script, boolean export)
script - print the DDL to the console
export - export the script to the database
Configuration cfg = new AnnotationConfiguration (). Configure ();
SchemaExport export = new SchemaExport (cfg);
export.create (true, true);
Or
new SchemaExport (new AnnotationConfiguration (). configure ()). create (false, true);

SessionFactory
1 used to generate and manage sesssion
2 Typically, each application requires only a SessionFactory, unless the case to access multiple databases
3 openSession () and openSession ()
 openSession () always creates a new session, need to manually close ().
 getCurrentSession () and automatically turn off auto-commit transaction. Obtained from the context of the session, if the environment does not exist at that time to create a new. If the environment exists for the use of the environment, and are the same each time by session ( presented in the session, before the new one after that). Usage: define transaction boundaries.
 see the context of the so-called profile
<property name="current_session_context_classs"> thread </ property>
Range jta | thread | managed | custom.Class

About JTA

Session
The task of managing a database unit, the management of the additions and deletions to the database search operation, commit the transaction.
Methods CRUD: save (), delete (), update (), saveOrUpdate (), load (), get (), clear ().
session.beginTransaction ();
session.save (Object obj);
session.getTransaction (). commit ();
session.close ();

get () and load () to find the time difference  , will give priority to find the cache from the session.
 find no corresponding record, the performance is different. Load method will not find no error, get error when you can not find.
 Load return a proxy object, until the real content of the object to use to launch SQL statement only. Get launched SQL statements directly from the database and will not delay.
Update () method
1 is used to update the detached object, update is complete as persistent.
2 update transient object error. Update their set id (provided that the id exists in the database) the transient object.
3 persistent objects can occur as long as the updated set of different fields
Part 4 Update changed fields (three methods)
 XML property tags set update = true | false property
annotation set @ Column (updatable = false) attribute, in this way less, not flexible.
 XML tag set the class dynamic-update = "true" attribute
A session can be the same, cross-session no. Implementations across session, but when the session can be used in the merge (). Merge method will start with the database load, and will be compared in the database and then update the field that have changed .
JPA1.0 Annotation no corresponding attribute, Hibernate
 Use HQL (EJBQL) (recommended)
clear () method:
Clear the session cache. Call clear () method forces the clear session cache. Does not deal with the database.
flush () method:
When the session's transaction commits, it will force from memory (session cache) to the database simultaneously. By default, the transaction is submitted to only sync session. Is not commonly used.

Query Interface

Here the relationship between relational mapping mapping refers to the relationship between objects, does not refer to databases. Relational mapping problem is that when the object is in the variety of relationships, how to map database tables, programming, how to deal with.
One to one: one-way (the primary key, foreign key), two-way (the primary key, foreign key)
One to many: one-way, two-way (and many to one the same way)
Many to one: one-way, two-way (bidirectional one to many and many to one-way is the same)
Many to many: one-way, two-way
(One to one single / two-way primary key association mapping, only for understanding)
Collection mapping: list, map, set
Inheritance mapping (understanding): single table, multiple tables, more than one child table main table components mapping: @ Embeddable, @ Embedded

One to one (one to one) one-way two objects are related one to one mapping relationship.
There are two strategies to achieve one to one association mapping  primary key association: that so that the two objects have the same primary key values, to show them one to one correspondence between; database table fields there will be no additional maintenance of the relationship between them, only by the primary key relationships to maintain. one to one mapping of primary keys associated with the default properties of the cascade, and its related objects will also be stored. So do not throw TransientObjectException exception.
 The only foreign key association: a foreign key association, could have been used for many to one configuration, but only if coupled with restrictions, but also one to one relationship can be expressed. Unique = "true".
Unidirectional, such as the Person-person_id; Add person information when the information associated with the corresponding two-way relationship person_id, loading any party, can be associated with the other side of the information.
Note that the primary key id generation strategy, foreign associated with another object identifier. <one-to-one> Usually used together.
Class Person (id, name, idCard),
Class IdCard (id, cardNo)

One to One (one way) on a primary key association mapping (understanding)
XML configuration is usually associated with one-way primary key id to use a particular builder.
<class name="Person" table="t_person">
<id name="id">
<generator>
<param name="property"> idCard </ param>
</ Generator>
</ Id>
<one-to-one name="idCard" constrained="true"/>
</ Class>
one-to-one field does not load, it tells how to load the referenced object HIBERNATE. how to load it, the default under the master key to load the referenced object. If t_person be found id = 2, automatic load t_idCard id = 2 in the object information. constrained = "true", that person is a foreign key primary key, that the current primary key constraint on the existence of idCard, the current primary key id as a foreign key reference to the idCard.
<param name="property"> idCard </ param> that person's id from idCard, which is shared idCard the primary key.
Annotation configuration-one (one-way) primary key association mapping. (BUG)
@ OneToOne
@ PrimaryKeyJoinColumn
A BUG, the system does not generate the primary key mapping. Recommended XML configuration.

One to one (one-way) association on a foreign key mapping many to one association and one-way is almost the same. The only difference is the way one association of the foreign key field in the unique constraint. This approach will generate a new table foreign key field. If you do not limit the only constraint outside the field, it will result in many to one association. One end of the specified number of unique = "true", which limits the multiplicity of the many side of one.
<class name="Person" table="t_person">
<id name="id">
<generator/>
</ Id>
<property name="name"/>
<Many-to-one name = "idCard" column = "addressId" unique = "true"
not-null = "true" />
</ Class>
Note TransientObjectException exception in this state. Be saved when you save the foreign key idCard, and then save the Person class.
Annotation one-way foreign key association configuration
@ OneToOne
@ JoinColumn (name = "fields specify the name of the generated foreign key")

One to one (two) primary key association mapping (understanding)
Person   IdCard. At the other end is also associated with a one-of-way mapping.
Model object
Person (id, name, idCard)
IdCard (id, cardNo, person), both sides hold each other's property reference.
One to one (two) associated with the primary key mapping configuration XML configuration created in IdCard map, <one-to-one name="person"/> Hibernate instructions how to load, by default, according to the primary key to load. That is based on one to one mapping of one-way, on the other end is also coupled with a one-way-one of the primary key association mapping.
In the end configuration Person
<class name="Person" table="t_person">
<id name="id">
<generator>
<param name="property"> idCard </ param>
</ Generator>
</ Id>
<one-to-one name="idCard" constrained="true"/>
</ Class>
Configuration at the other end IdCard
<class name=" IdCard "table="t_idCard">
<id name="id">
<generator/>
</ Id>
<property name="cardNo"/>
<one-to-one name="person" property-ref="idCard" />
</ Class>
One to one (two) primary key association mapping Annotation (a BUG)
At both ends with the respective reference attributes
@ OneToOne
@ PrimaryKeyJoinColumn

One to one (two) the only foreign key mapping
Person  ----  IdCard. At the other end is also associated with a one-of-way mapping.
Object in the model
Person (id, name, idCard)
IdCard (id, cardNo, person),
Both sides hold each other's property reference.
Needed at the other end with <one-to-one>, indicating hibernate how to load, by default, according to load the primary key person; because the foreign key association mapping, the relationship between two entities by the person to maintain a foreign key idCard , so the person can not specify the primary key to load the person, but according to the person of the foreign key idCard to load the person object.
Two-way foreign key mapping one to one correlation XML configuration
Person end: many to one configuration with the formation of one to one foreign key unique configuration.
<class name="Person" table="t_person">
<id name="id">
<generator/>
</ Id>
<property name="name"/>
<many-to-one name="idCard" column="addressId" unique="true"/>
</ Class>
IdCard end: one to one, the other end of foreign key references
<class name=" IdCard "table="t_idCard">
<id name="id">
<generator/>
</ Id>
<property name="cardNo"/>
<one-to-one name="person" property-ref="idCard"/>
</ Class>
To load idCard, if not property-ref, default under the primary key id to load the person, property-ref = "idCard" to instructions from the person inside the idCard hibernate properties to load.
One-way foreign key association mapping Annotation configuration attributes both sides hold a reference to other relational model
Husband (id, name, wife)
Wife (id, name, husband)
Husband wife at the end of the attribute annotations
@ OneToOne
/ / @ JoinColumn
Wife husband at one end with comments, mappedBy
@ OneToOne (mappedBy = "wife") with reference to property in the wife mappedBy property after the end of this property of the association is set on the wife. Would not generate managing the husband wife this side of the set. Generated wife does not form field will be husband.
Rule: when two-way association will usually set mappedBy.

Joint primary key mapping one to one-way foreign key object model
Wife (id, name, age) WifePk (id, name)
Husband (id, name, wife)
1 in the Wife of the primary key generation strategy to establish a joint
@ IdClass (WifePk.Class)
@ Id
2 Husband to add a foreign key to
@ OneToOne
3 custom foreign key name Husband
@ OneToOne
@ JoinColumns (
{
@ JoinColumn (name = "wifeId", referencedColumnName = "id"),
@ JoinColumn (name = "wifeName", referencedColumnName = "name")
}
)
XML configuration: a little

Object-relational mapping component: an object is a database table to another part of the object: is a table
Annotation: @ Embeddable, @ Embedded
XML: <component>
Object Model
Husband (id, name, wife)
Wife (wifeName, wifeAge)
Annotation:
Property in Husband's wife comments on the establishment of
@ Embedded indicates that the object is embedded over from another location, do not need a separate mapping table.
Table generated in this way husband (id, name, wifename, wifeage), does not generate wife tables.
@ AttributeOverride annotation property can override the embedded objects corresponding to the column mapping:
XML:
<class name="Husband">
<id name="id">
<generator/>
</ Id>
<property name="name"> </ property>
<component name="wife">
<property name="wifeName"/>
<property name="wifeAge"/>
</ Component>
</ Class>

Many to one (many to one) unidirectional many to one mapping of database design principles: that the lower increase in the number of foreign keys
/ / Note that the entity class property is created with the SQL statement should be avoided the same name in the keyword.
Many to one unidirectional mapping entity model (User many-to-Group)
User (id, name, group) and more
Group (id, groupname) a

Annotation Configuration
@ Entity
@ Table (name = "t_group") / / Note that the table name with SQL, only need to keyword the same name more than one end of the User property of the annotation group configuration
@ ManyToOne
@ JoinColumn (name = "groupId")
XML configuration
<many-to-one name="group" column="groupId" />
Tab in the "many" end of the add foreign key, which is equivalent to add the foreign key in the database table generated by user (id, name, groupid), t_group (id, groupname)
Property cascade
<many-to-one name="group" column="groupid" cascade="all"/>
Values all, none, save-update, delete, cascade operation between objects, only the additions and deletions to work.
User in the store, set the cascade = "all" will be automatically stored in the corresponding t_group. But not control user associated with the object (normally stored in the associated object will give priority to, and then store the user).

One to many (one to many) one-way association mapping model (group-to-many user)
Group (id, name, users) of a
User (id, name) more than the design of this side of the existence of a number of collections, the resulting database table is usually generated in more than one end of the foreign key.
Set <User> users = new HashSet <User> ()
One-way foreign key mapping one to many association this side of a Group comments on the end users configure properties
@ OneToMany
@ JoinColumn (name = "groupId")
If you do not specify the foreign key column generated @ JoinColumn (name = "groupId"), the default will generate many to many relationships, resulting in an intermediate table.
XML configuration in the configuration that one end of a Group
<class name="com.hibernate.Group" table="t_group">
<id name="id">
<generator/>
</ Id>
<property name="name"/>
<set name="users">
<key column="groupId"/> specify the name of the foreign key field generated
<one-to-many/>
</ Set>
</ Class>

Law:
 way, the existence of the other party to the reference, embodied in a database table foreign key. Configuration is generally used when the configuration at one end.
 Two-way, the two cross-reference each other, to both ends of the two-way configuration. Annotation-based two-way configuration, at one end configured, on the other end must be specified mappedby property.
 On-many / many-to-database design, plus the many side is always in the foreign key. Usually generated more than one end of the specified foreign key name.

One to many / many-to-many and many-to-two-way associated with two-way association is the same situation.
Relational model (group-to-many user)
Group (id, name, users) of a
User (id, name, group) and more
Set <User> users = new HashSet <User> ()
Configuration rules: generally more than one end of the main, more than one end of the first configuration at one end in a multi-client configuration group User
@ ManyToOne
In one end of the Group ended configuration, the users only need to add a mappedBy = "group"
@ OneToMany (mappedBy = "group")
XML configuration
Group of
<set name="users">
<key column="groupId"/>
<one-to-many/>
</ Set>
In the User in
<many-to-one name="group" column="groupId"/>
Always ensure that the generation of more than one end of the generated foreign key and a foreign key party generated the same name, both for groupId.
If a different name will be generated at the end of the extra number of foreign keys.
create table t_group (
id integer not null auto_increment,
name varchar (255),
primary key (id)
)
create table t_user (
id integer not null auto_increment,
name varchar (255),
groupId integer,
primary key (id)
)
alter table t_user
add index FKCB63CCB6C3D18669 (groupId),
add constraint FKCB63CCB6C3D18669
foreign key (groupId) references t_group (id)

For example-many unidirectional relationship: teachers  students, teachers need to know what to teach students, but students do not know what the teacher is to teach.
Database: middle table
Annotation: @ ManyToMany
XML: <many-to-many>
Relational model (Teache-many Student), from the Teacher of the end can relate to students.
Teacher (id, name, students) and more
Student (id, name) more
Set <Student> students = new HashSet <Student> ()
Teacher in the configuration that one end of the
@ ManyToMany
If you manually specify the intermediate form of the table names and field names
@ JoinTable (
name = "t_s", / / table name
joinColumns = {@ JoinColumn (name = "teacher_id ")},// point to teacher table
inverseJoinColumns = {@ JoinColumn (name = "student_id ")}// point to another table
)
The resulting table
create table Student (
id integer not null auto_increment,
name varchar (255),
primary key (id)
)
create table Teacher (
id integer not null auto_increment,
name varchar (255),
primary key (id)
)
create table t_s (/ / generated in the middle of the table
teacher_id integer not null,
student_id integer not null,
primary key (teacher_id, student_id)
)
t_s table references the other two properties are the primary key of the table.
XML,
<class name="com.xxx.Teacher">
<id name="id">
<generator/>
</ Id>
<property name="name"/>
<set name="students" table="t_s"> table table name defined in the middle of the table
<key column="teacher_id"> </ key>
<many-to-many column="student_id"/>
</ Set>
</ Class>

For example-many two-way relationship: the teacher   students, teachers need to know what to teach students, and students know what teachers.
Database: middle table
Annotation: @ ManyToMany
XML: <many-to-many>
Many to many one-way configuration requires only one end is configured on it.
Relational model (Teache-many Student)
Teacher (id, name, students) and more
Student (id, name, teachers) and more
Set <Student> students = new HashSet <Student> ()
Set <Teacher> teachers = new HashSet <Teacher> ();
Annotation configuration Teacher configured on the side of the students
@ ManyToMany
@ JoinTable (name = "t_s",
joinColumns = {@ JoinColumn (name = "teacher_id")},
inverseJoinColumns = {@ JoinColumn (name = "student_id")}
)
Student teachers at one end only need to configure
@ ManyToMany (mappedBy = "students")
XML configuration: both ends of the configuration, the attention to the middle of the table names and table field generated by the property name to be consistent
Configuration that one end of the Teacher
<set name="students" table="t_s">
<key column="teacher_id"/>
<many-to-many column="student_id"/>
</ Set>
One end of the Student Configuration
<set name="teachers" table="t_s">
<key column="student_id"> </ key>
<many-to-many column="teacher_id"/>
</ Set>
The resulting database table is the same as above.

Tree design (important)
Design: database model, object-oriented model, relational mapping, CRUD
Database Model: Table (id, name, pid)
Physical model: the parent node   child one to many nodes, one to many / many to one bidirectional association mapping, only one node of a parent child node, a parent node several child nodes.
Class Org
private int id;
private String name;
private Set <Org> children = new HashSet <Org> ();
private Org parent;
Relational Mapping: the use of the same class @ ManyToOne and @ OneToMany
Parent on the parent node
@ ManyToOne
@ JoinColumn (name = "parent_id")
public Org getParent () {
return parent;
}
On children in the child node
@ OneToMany (cascade = CascadeType.ALL, mappedBy = "parent")
public Set <Org> getChildren () {
return children;
}

Basic CRUD object relationship
1 want to delete or update, do first load, unless the precision that ID.
2 Cascade property (an array) to manage CUD, just for programming convenience, not to see too much of its functionality.
cascade = {CascadeType.ALL}
CascadeType value
All ALL Cascade all operations
MERGE Cascade merge operation merge (merge = save + update)
PERSIST Cascade persist operation storage persist ()
REFRESH Cascade refresh operation to refresh
REMOVE Cascade remove operation to delete rules, two-way relationship bidirectional association if the program set. Also set mappedBy
3 Fetch attributes, read, manage R (Retrieve Query)
fetch = FetchType.LAZY | EAGER
Hibernate Annotation of FetchType in ManyToOne default is EAGER, in OneToMany is the default LAZY.
If you specify OneToOne the fetch = FetchType.LAZY, will delay the loading of related objects, whether load or get.
In XML, the foreign key attribute set inverse = "true | false" set.
4 If you want to eliminate relationship, first set the relationship can break the relationship NULL, then delete the corresponding record. If you do not delete the related records, the record becomes garbage. (PITT: You can also use the HQL: session.createQuery (
Delete User u where u.id = 1))

5 O / R Mapping programming model
A mapping model (map database)
1 JPA ANNOTATION
2 hibernate annotation extension
3 hibernate xml
4 jpa xml
B programming interface (additions and deletions to search)
1 jpa
2 hibernate
C database query language
1 HQL
2 EJBQL (JPQL)
6
PITT: JPA hibernate function is a subset.
Collection of maps (not important)
Set
List
@ OrderBy ("property name ASC | DESC")
Map
@ MapKey (name = "field name")
private Map <Integer, User> users = new HashMap <Integer, User> ();

Inheritance mapping (not important)
Three modes: TABLE_PER_CLASS | JOINED | SINGLE_TABLE
strategy = InheritanceType.XXX
Relationship model is a way to the table in the database has three forms.
SINGLE_TABLE mode
Person, Student and Teacher successor Person
Person (id, name)
Student (score)
Teacher (title)
Entities in the Student
@ Entity
@ DiscriminatorValue ("student")
Teacher of the
@ Entity
@ DiscriminatorValue ("teacher")
In Person in
@ Entity
@ Inheritance (strategy = InheritanceType.SINGLE_TABLE)
@ DiscriminatorColumn (name = "discriminator", discriminatorType =
DiscriminatorType.STRING)
@ DiscriminatorValue ("person")
The resulting table
create table Person (
discriminator varchar (31) not null,
id integer not null auto_increment,
name varchar (255),
score integer,
title varchar (255),
primary key (id)
)
TABLE_PER_CLASS model is also more troublesome in this way, pay attention to id generation strategy.
Person, Student and Teacher successor Person
Person (id, name)
Student (score)
Teacher (title)
In Person in
@ Entity
@ Inheritance (strategy = InheritanceType.TABLE_PER_CLASS)
@ TableGenerator (/ / ID generation strategy using the table generation strategy
name = "t_gen",
table = "t_gen_table",
pkColumnName = "t_pk",
valueColumnName = "t_value",
pkColumnValue = "person_pk",
initialValue = 1,
allocationSize = 1
)
Primary key mapping
@ Id
@ GeneratedValue (generator = "t_gen", strategy = GenerationType.TABLE)
Generates three tables + a primary key of the temporary table generated
create table Person (
id integer not null,
name varchar (255),
primary key (id)
)
create table Student (
id integer not null,
name varchar (255),
score integer not null,
primary key (id)
)
create table Teacher (
id integer not null,
name varchar (255),
title varchar (255),
primary key (id)
)
create table t_gen_table (
t_pk varchar (255),
t_value integer
)
JOINED the simplest model in this way.
Person, Student and Teacher successor Person
Person (id, name)
Student (score)
Teacher (title)
In Person in
@ Entity
@ Inheritance (strategy = InheritanceType.JOINED)
The resulting table:
create table Person (
id integer not null auto_increment,
name varchar (255),
primary key (id)
)
create table Student (
score integer not null,
id integer not null,
primary key (id)
)
create table Teacher (
title varchar (255),
id integer not null,
primary key (id)
)
Two foreign key constraint table inside the Student and Teacher of the id were references Person (id)

Hibernate query (HQL)
QL (Query Language)
NativeSQL> HQL> EJBQL (JP QL1.0)> QBC (Query by Criteria)>
QBE (Query by Example)
EJBQL is a subset of HQL.
HQL is no need to distinguish between EJBQL and was particularly clear, to meet the requirements and design.
Relationship between QL and navigation combined together to provide services for the query.

: Placeholder
Query q = session.createQuery ("from Category c where c.id>: min and c.id <: max");
q.setParameter ("min", 2);
q.setParameter ("max",;
Or q.setInteger ("min", 2);
q.setInteger ("max",;
Similar to the JDBC PreparedStatement inside

Chain Programming
Query q = session.createQuery ("from Category c where c.id>: min and c.id <: max")
. SetInteger ("min", 2)
. SetInteger ("max",;

Query q = session.createQuery ("from Category c where c.id>? And c.id <?");
q.setParameter (0, 2)
. SetParameter (1,;

Pagination
Query q = session.createQuery ("from Category c order by c.name desc");
q.setFirstResult (2); / / set the initial recording position.
q.setMaxResults (4); / / set the maximum number of records per page

q.uniqueResult () / / return only one record.

Is null
Is empty test set is empty

NamedQueries named query to query in a centralized location.
SQLQuery q = session.createSQLQuery ("select * from category limit 2,4"). AddEntity (Category.class);

The use of a database

Performance Optimization
1 Note session.clear () use, especially when the loop is constantly paging
A collection in a large traverse, out of which the object containing sensitive words
B another form of memory leak.
2 1 + N problem
LAZY, BatchSize, join fetch
3list and the difference between iterator
check list of all
iterator first take ID, wait until then to use the time to remove the object based on ID.
the second session in the list issued to the database will query the data. iterator first look for a second session-level cache.

4-level cache and second level cache and query cache
A cache
B-level cache, session level cache
C secondary cache, SessionFactory-level cache, there can be level across the session.
Frequently accessed, the modifications are minor do not often visit a limited number.
D Open the secondary cache
Hibernate.cfg.xml
<property name="cache.use_second_level_cache"> true </ property>
Use ehcache
JAR file: \ lib \ optional ehcache-1.2.3.jar
<property name="cache.provider_class"> org.hibernate.cache.EhCacheProvider </ property>
Using the configuration file ehcache.xml, copy it to src directory.
Annotation annotation: @ Cache
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
@ Cache (usage = CacheConcurrencyStrategy.READ_WRITE)
@ Cache (
CacheConcurrencyStrategy usage (); (1)
String region () default ""; (2)
String include () default "all"; (3)
)
(1) usage: the given cache concurrency strategy (NONE, READ_ONLY, NONSTRICT_READ_WRITE, READ_WRITE, TRANSACTIONAL)
(2) region (optional): buffer range (defaults to the class of fully qualified class name or collection role of the fully qualified name)
(3) include (optional): value of all properties to include all (proterty), for the non-lazy to only include non lazy properties (default all)
E load default secondary cache, iterator default secondary cache
F list the default add data to the secondary cache, but when the query is not used.
G If you need to use Query secondary cache, then open the query cache
<property name="cache.use_query_cache"> true </ property>
Call Query setCachable (true) method specified in the use of secondary cache.

Services
ACID
Atomic (Atomicity), consistency (Consistency), isolation (Isolation), persistent (Durability).
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Shangxue Tang Hibernate Notes

  • log4j easy application in java

    JAVA development, frequently used the log output, in a so-called most of the software company will have its own set of configuration style, re-read the configuration file to initialize property of the log, it will be good, but sometimes may not need to fu

  • jboss ejb3 Message Driven Bean

    Super Medium ejb hate. . . . . . . . . . . . . . . . . . . ================================================ To configure a Message Driven Bean in a different application server parameters are not the same. Currently only passed the test jboss. Message Dri

  • java read file

    java read documents in two ways: java.io and java.lang.ClassLoader When using the java.io, when java.lang.ClassLoader use it? (Note: If prior to read xml file java read file clearly aware of these two methods have been like! Can take much less to understa

  • Hibernate configuration parameters hibernate.hbm2ddl.auto

    Hibernate in the configuration file: <properties> <property name="hibernate.hbm2ddl.auto" value="create" /> </ properties> Parameter Description: validate load hibernate, the authentication to create a database t ...

  • Spring + Hibernate to use Glassfish Database Connection Pool

    applicationContext.xml file content <? xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = " http://www.springframework.org/schema/beans " xmlns: xsi = " http://www.w3.org/2001/XMLSchema-instance " ...

  • The EJB3 Persistence

    EJB3 persistence with Hibernate is very similar to the mechanism: Environment: Server: JBOSS5.0 Database: MySQL5.0 1. Set up a data source First of all, in jboss-5.0.0.GA \ server \ default \ deploy, the establishment of a database used to connect the dat

  • hibernate to use the principle of

    The use of hibernate, implementation of data persistence. Has the following several processes. One configuration database connection information. Hibernate.config 2 configuration mapping. 3 use: the use of the process are the following steps: 3.1: Ge ...

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co

  • spring struts2.0 hibernate environmental structures .. despair carried out more than one hour only with good.

    http://www.qqread.com/java/2008/06/f413762.html Look here. . Note added myeclipse support spring when necessary add the commons-dbcp database connection pool package. And to add hibernate support. . Finally add struts2 support. . Oh the lazy point. . . fu

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries