This article will describe the basic configuration of hibernate and the application of the configuration file, which is very important for the correct proficiency in the use of hibernate.
detailed mapping elements in the configuration file
The mapping of object relationships is illustrated with an XML document. Mapping documents can be generated using tools such as Xdoclet,middlegen and Andromda. The following is an example of a mapping to explain the mapping element, the mapping file code is as follows.
<?xml version= "1.0"? > >
!--
All XML mapping files need to be defined as the doctype shown below.
Hibernate will first search for the DTD file in its classpath (Classptah).
-->
! DOCTYPE hibernate-mapping Public
"-//hibernate/hibernate Mapping DTD 3.0//en"
"Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
!--
Hibernate-mapping has several optional properties:
The Schema property indicates the schema name of the mapped table.
The Default-cascade property specifies the default cascading style desirable values are none, save, update.
The Auto-import property defaults to allow us to use a class name with a unqualified name in the query language to have a value of true and false.
The Package property specifies a package prefix.
-->
Auto-import= "true" package= "test" >
!--define a persistent class with the class element-->
<class name= "People" table= "person"
The!--ID element defines the mapping of the property to the primary key field of the database table. -->
<ID name= "id" >
!--used to generate a unique identity for an instance of the persisted class-->
<generator class= "native"/>
</id>
The!--discriminator recognizer is a mapping method for defining the inheritance relationship-->
<discriminator column= "Subclass" type= "character"
The!--property element declares a persisted, JavaBean-style attribute for a class-->
<property name= "Name" type= "string"
<column name= "name" length= "not-null=" "true"/"
</property>
<property name= "Sex"
Not-null= "true"
Update= "false"/>
!--Multi-pair mapping relationship-->
<many-to-one name= "Friend"
Column= "friend_id"
Update= "false"/>
!--Setting Association Relationship-->
<set name= "Friends" inverse= "true" order-by= "id" >
<key column= "friend_id"/>
<!-pair of multiple maps-->
<one-to-many class= "Cat"/>
</set>
</class>
method of component application
There are two types of components, namely, components (component) and dynamic components (dynamic-component). In a configuration file, the component element establishes a mapping relationship between the elements of a child object and the fields of the corresponding table in the parent class. The components can then declare their own properties, components, or collections. The component element is defined as follows:
<component name= "PropertyName" class= "ClassName" insert= "True|false"
Upate= "True|false" access= "field|property| ClassName ">
<property .../>
<many-to-one .../>
........
</component>
In this code, name refers to the property name, class is the name of the type, and insert refers to whether the mapped field appears in the SQL INSERT statement, upate indicates whether the mapped field appears in the SQL UPDATE statement, and access indicates the policy for accessing the property.
Basic configuration of Hiebernate
The Hibernate database connection information is loaded from the configuration file. There are two forms of hibernate configuration files: One is an XML-formatted file and one is the Properties property file. The default file name for the configuration file in properties form is hibernate.properties, and a configuration file in the form of properties is as follows:
#指定数据库使用的驱动类
Hibernate.connection.driver_class = Com.mysql.jdbc.Driver R
#指定数据库连接串
Hibernate.connection.url = jdbc:mysql://localhost:3306/db
#指定数据库连接的用户名
Hibernate.connection.username = user
#指定数据库连接的密码
Hibernate.connection.password = password
#指定数据库使用的方言
Hibernate.dialect = Net.sf.hibernate.dialect.MySQLDialect
#指定是否打印SQL语句
Hibernate.show_sql=true
The configuration file contains a set of properties that the hibernate will use to connect to the database.
In an XML-formatted configuration file, in addition to the basic Hibernate configuration information, you can specify a specific persisted class's mapping file, which avoids hard-coded the persisted class's configuration file into the program. The default file name for a configuration file in XML format is Hibernate.cfg.xml, and an example of an XML configuration file is shown below:
<?xml version= ' 1.0 ' encoding= ' UTF-8 '? > >
! DOCTYPE hibernate-configuration Public
"-//hibernate/hibernate Configuration DTD 3.0//en"
"Http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
<session-factory>
!--display the executed SQL statement-->
<property name= "Show_sql" >true </property>
!--Connection String-->
<property name= "Connection.url" >jdbc:mysql://localhost:3306/stu </property>
!--user name to connect to the database-->
<property name= "Connection.username" >root </property>
!--Database user Password-->
<property name= "Connection.password" >root </property>
!--Database Driver-->
<property name= "Connection.driver_class" >com.mysql.jdbc.driver </property>
Dialect--> selected for use in!--
<property name= "dialect" >org.hibernate.dialect.mysqldialect </property>
!--Mapping File-->
<mapping resource= "Com/stuman/domain/admin.hbm.xml"/>
!--Mapping File-->
<mapping resource= "Com/stuman/domain/student.hbm.xml"/>
</session-factory>
Configuration files in properties form and XML-formatted profiles can be used at the same time. When two types of configuration files are used concurrently, the settings in the XML configuration file overwrite the same properties of the properties configuration file.
Object identification Symbol
In relational database tables, the primary key (Primary key) is used to identify records and to ensure uniqueness of each record. In the Java language, you can determine whether two objects are equal by comparing the memory addresses of the objects referenced by two variables, or by comparing the same object values referenced by two variables. Hibernate to address the difference between the two, use the object identifier (OID) to identify the uniqueness of the object. An OID is the equivalent of a primary key in a relational database in the Java object model. At run time, Hibernate maintains the correspondence between Java objects and the records in the database table based on the OID. As shown in the following code, the load () method of the session was called three times, loading the user object of the OID to 1 or 3, respectively.
Transaction tx = Session.begintransaction ();
User User1 = (user) session.load (user.class,new Long (1));
User User2 = (user) session.load (user.class,new Long (1));
User User3 = (user) session.load (user.class,new Long (3));
System.out.println (user1 = = User2);
System.out.println (user1 = = User3);
When the application executes the above code, it first loads the user object with the OID 1, looks for the record with ID 1 from the database, creates the corresponding user instance, saves it in the session cache, and finally assigns the reference to the instance to the variable user1. When an object that has an OID of 1 is loaded, the reference to the instance of the OID in the session cache is assigned directly to the variable user2. Therefore, the result of an expression User1==user2 is true.
Identity builds can use different policies, and table 1 is a built-in identity generation policy for hibernate.
Table 1 Hibernate identity Generation policy
Identifier Builder
|
Describe |
Increment |
Applies to proxy primary keys. Automatically generated incrementally by hibernate. |
Identity |
Applies to proxy primary keys. Generates an identifier from the underlying database. |
Sequence |
Applies to proxy primary keys. Hibernate generates identifiers based on the sequence of the underlying database, which requires the underlying database to support the sequence. |
Hilo |
Applies to proxy primary keys. Hibernate branch High/low algorithm generation identifier. |
Seqhilo |
Applies to proxy primary keys. Use a high/low algorithm to efficiently generate long,short or int type identifiers. |
Native |
Applies to proxy primary keys. Automatically select identity, sequence, or Hilo, depending on how the underlying database automatically generates identifiers. |
Uuid.hex |
Applies to proxy primary keys. Hibernate uses a 128-bit UUID algorithm to generate an identifier. |
Uuid.string
|
Applies to proxy primary keys. The UUID is encoded into a 16-character string. |
Assigned |
Applies to natural primary keys. The Java application is responsible for generating the identifier. |
Foreign |
Applies to proxy primary keys. Use an identifier for another associated object. |
Hibernate mapping Type
In an object/relationship mapping file, Hibernate uses the mapping type as a bridge between Java types and SQL types. There are 2 types of hibernate mappings: built-in mapping types and custom mapping types.
1. Built-in mapping type
Hibernate defines the built-in mapping types for all Java native types, common Java types such as String, date, and so on. Table 2 lists the Hibernate mapping type, the corresponding Java type, and the corresponding standard SQL type.
Table 2 Hibernate built-in mapping type
Hibernate mapping Type |
Java type |
Standard SQL type |
Size |
Integer/int |
Java.lang.integer/int |
INTEGER |
4 bytes |
Long |
Java.lang.long/long |
BIGINT |
8 bytes |
Short |
Java.lang.short/short |
SMALLINT |
2 bytes |
Byte |
Java.lang.byte/byte |
TINYINT |
1 bytes |
Float |
Java.lang.float/float |
FLOAT |
4 bytes |
Double |
Java.lang.double/double |
DOUBLE |
8 bytes |
Big_decimal |
Java.math.BigDecimal |
NUMERIC |
|
Character |
Java.lang.character/java.lang.string/char |
CHAR (1) |
Fixed-length characters |
String |
Java.lang.String |
VARCHAR |
Variable length character |
Boolean/yes_no/true_false |
Java.lang.boolean/boolean |
BIT |
Boolean type |
Date |
Java.util.date/java.sql.date |
DATE |
Date |
Timestamp |
Java.util.date/java.util.timestamp |
TIMESTAMP |
Date |
Calendar |
Java.util.Calendar |
TIMESTAMP |
Date |
Calendar_date |
Java.util.Calendar |
DATE |
Date |
Binary |
Byte[] |
Blob
|
Blob |
Text |
Java.lang.String |
TEXT |
Clob |
Serializable |
Any Java class that implements the Java.io.Serializablej interface |
Blob |
Blob |
Clob |
Java.sql.Clob |
Clob |
Clob |
Blob |
Java.sql.Blob |
Blob |
Blob |
Class |
Java.lang.Class |
VARCHAR |
Fixed-length characters |
Locale |
Java.util.Locale |
VARCHAR |
Fixed-length characters |
TimeZone |
Java.util.TimeZone |
VARCHAR |
Fixed-length characters |
Currency |
Java.util.Currency |
VARCHAR |
Fixed-length characters |
2. Custom mapping Type
Hibernate provides a custom mapping type interface that allows users to programmatically create custom mapping types. User-defined mapping types need to implement Net.sf.hibernate.UserType or Net.sf.hibernate.CompositeUserType interfaces. The specific way to create a custom mapping type is to refer to the Hibernate official documentation or related information, which is not described here in detail.