Learning Framework, configuration is not rare, with the configuration, the framework will know what we want to do before we know how to perform the operation we need!
Hibernate configuration file, generally divided into two parts:
1. Master profile Hibernate.cfg.xml file, typically placed under Classpatn path
2. map file Xxx.hbm.xml file, usually with entity class under the same package
The former is the configuration related database and the introduced mapping file information, while the latter mainly configures the mapping relationship between the object and the table;
Note: The path of the configuration file, individual, and some will map files collectively put together also have, so see a person likes, there is no mandatory rules how to store.
The following is the Hibernate.cfg.xml file configuration information, in order to facilitate the memory, we have this configuration file configuration information in three categories:
1. Database information: dialect, URL, username, password, database driver, configure with <property> tag
2. Mapping file information: that is, the mapping between the object and the table, with the <mapping> tag to configure
3. Other configuration information: whether to display SQL statements, formatted SQL, level two cache configuration, etc., to configure with <property> tags
<!DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hibernate. Org/dtd/hibernate-configuration-3.0.dtd "><hibernate-configuration> <session-factoryname= "Foo"> <!--Configure Database Information - <!--Configure database dialect - < Propertyname= "Hibernate.dialect">Org.hibernate.dialect.MySQLDialect</ Property> <!--Configure the database URL - < Propertyname= "Connection.url">Jdbc:mysql:///hibernate</ Property> <!--Configure database driver (MySQL) - < Propertyname= "Connection.driver_class">Com.mysql.jdbc.Driver</ Property> <!--Configure database user name - < Propertyname= "Connection.username">Root</ Property> <!--Configure Database Password - < Propertyname= "Hibernate.connection.password">1208</ Property> <!--whether to display SQL - < Propertyname= "Hibernate.show_sql">True</ Property> <!--Import a map file This is the correspondence between the entity and the database table - <MappingResource= "Com/hibernate/user.hbm.xml"/> </session-factory></hibernate-configuration>
The following is the map file base configuration, the basic configuration is relatively simple, followed by the associated configuration, collection configuration, through annotation configuration and so on:
For the convenience of memory, the basic configuration is divided into the following categories:
1. Because the configuration file is the relationship between the configuration object and the table, the corresponding entity must be configured with the package path, which is configured with the
2. Then start to configure the relationship between the entity and the table, use the <class> tag configuration, configure the entity name through the Name property, and configure the table name through the table property;
3. Theoretically, each table should be set a primary key, so you should configure the primary key ID, use the <id> tag to configure;
4. The attribute of the entity corresponds to the column name of the table, and is configured using <property>;
The following base configuration code will prevail:
<?XML version= "1.0"?><!DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourcefo Rge.net/hibernate-mapping-3.0.dtd "><!--entity class package path -<hibernate-mapping Package= "Com.hibernate"> <!--the name of the entity, the corresponding table name - <classname= "User"Table= "Sys_user"> <!--primary key ID, primary key ID type, column name in table - <IDname= "id"type= "int"column= "id"> <!--Automatic growth - <Generatorclass= "Native"/> </ID> <!--Entity property name, entity attribute type, column name in table - < Propertyname= "Name"type= "string"column= "Name"length= " the"/> </class></hibernate-mapping>
Primary key properties (configured with <id> tags) configuration instructions:
Primary key attributes, which are configured with the <id> tag, it is important to note that the object properties corresponding to the primary key in the table are best decorated with wrapper classes, such as the name of the primary key in the table as the ID, and the property in the corresponding object (assuming also called ID). It's best to declare the private Integer ID Because if the private int ID is used to declare, the initial value of ID is 0, if the ID is declared with an integer, then the initial value is NULL, if the ID is null means there is no correspondence with the table data in the database that the database does not exist.
Child elements are configured with <generator> tags, which are used for the primary key generation strategy, and the commonly used values are:
Assigned: Represents the manually specified ID, which means that the ID value must be specified when inserting data into the table;
Native: According to the ability of the underlying database, choose one of identity, sequence, Hilo;
Identity: Use the database's primary key generation strategy, noting that not all databases support the auto-growth strategy;
Sequence: Use this strategy in DB2, Oracle, PostgreSQL;
Increment: Query The maximum value of the ID in the table, then maintained by Hibernate +1, but not recommended, because there will be problems in the multi-threaded;
UUID: The UUID is automatically generated by hibernate and specified as the primary key value, resulting in values such as 4dehs4523232jdkaldajklfdkaj (similar);
Hilo: Generating primary key values according to the high-status algorithm requires the following configuration
<generator class= "Hilo" >
<param name= "Table" >htbl</param>
<param name= "column" >next_value</param>
<param name= "Max_lo" >100</param>
</generator>
The HTBL table has only one field next_value, which is used to record Sys_user tables that have been inserted several times, and the Max_lo property is used to set data values for each increment, such as inserting Sys_user table data for the first time, then Htbl next_ The value is updated to the ID value in the 1,sys_user table as well as 1, and the Sys_user table is inserted again, then the Next_value value of HTBL is updated to 2, when the data is inserted in the Sys_user table, and the row ID of the inserted data becomes 101. From the second start of the insertion, the Sys_user row ID is controlled by the attribute Max_lo. The advantage of this strategy is that you need only an extra table, and all the data is supported.
Summary: General use of native, the configuration of the database will not need to modify the value. But depending on the situation, such as using Oracle, we know that the primary key policy uses sequence, which is directly configured as sequence.
General properties (non-<id> tag configuration, referring to <property> configuration) configuration instructions:
Name property: The name of the object or the property of the object, which must be there;
Type property: Indicates the types, if not written, Hibernate will automatically detect, can write the full name of the class in Java or write hibernate type, personal custom is to write hibernate type, such as String type strings, numeric type int, Date type is dated and so on, you can refer to the mapping type below table and date type comparison table ;
Column property: The name of the columns in the corresponding table, if not, defaults to the property name, but note that the column property must be specified when the name of the property and the keyword in the table are the same, such as <property name= "desc"/> If the default property name, Then the execution of the program will be error, because DESC and SQL sort keyword desc, then we can add the property to Column= "Desc_", if you must use DESC for the column name, then modify the column property is column= "' desc '";
Length property: Lengths, not all types have length attributes, such as varchar, but int does not;
Not-null property: Non-null constraint, default = False
Note: If there are binary attributes in the entity, such as private byte[] photo, then the HBM file must be configured as
<property name= "photo" type= "binary" length= "102400" column= "Photo"/>
The above is the configuration method of binary attributes in Hibernate mapping file
Hibernate mapping type comparison table
Java type |
Hibernate mapping Type |
SQL type |
Java.math.BigDecimal |
Big_decimal |
Numeric |
Byte[] |
Binary |
varbinary (BLOB) |
Boolean (Java.lang.Boolean) |
Boolean |
Bit |
Byte (java.lang.Byte) |
Byte |
tinyint |
Java.util.Calendar |
Calendar |
Timestamp |
Java.sql.Clob |
Clob |
Clob |
Java.util.Date or Java.sql.Date |
Date |
Date |
Double (java.lang.Double) |
Double |
Double |
Float (java.lang.Float) |
Float |
Float |
Int (Java.lang.Integer) |
Integer |
Integer |
Java.util.Local |
Local |
varchar |
Long (Java.lang.Long) |
Long |
bigint |
An instance of Java.io.Serializable |
Serializable |
varbinary (or BLOB) |
Java.lang.String |
String |
varchar |
Java.lang.String |
Text |
Clob |
Java.util.Date or Java.sql.Timestamp |
Time |
Timestamp |
Hibernate mapping types for Java date and time types
Mapping type |
Java type |
Standard SQL Type |
describe |
Date |
Java.util.Date or java.sql.Date |
DATE |
Represents a date in the form of: Yyyy-mm-dd |
Time |
Java.util.Date or java.sql.Time |
Time |
Representing time in the form of: HH:MM:SS |
Timestamp |
Java.util.Date or java.sql. Timestamp |
TIMESTAMP |
Represents time and date in the form of: Yyyymmddhhmmss |
Calendar |
Java.util.Calendar |
TIMESTAMP |
Ditto |
Calendar_date |
Java.util.Calendar |
DATE |
Represents a date in the form of: Yyyy-mm-dd |
These entity-to-table mapping relationship configuration information can be configured before the table is created, or it can be configured after the table is created, what does it mean?
This means that we don't have to create a table. Of course, do not want to create a table, but also need to configure, let Hibernate help us go to the database to create the table (automatically help us generate table structure), in the Hibernate.cfg.xml file, in our so-called other configuration area, configuration <property name= " Hbm2ddl.auto ">CREATE</PROPERTY> So when the program is run, Hibernate automatically maps the table information according to the mapping file, and goes to the database to create the table structure.
However, it is important to note that, after each execution of the program, Hibernate will help us go to the database to find out if the table exists, delete it if it exists, create the table directly if it does not exist, and the disadvantage is that it will not preserve the database table information, and the table will be deleted and recreated after each execution of the program.
If you want to avoid this situation, change the above configuration to <property name= "Hbm2ddl.auto" >UPDATE</PROPERTY>, so configured, when the program is executed, the Hibernate table does not exist, is created, the discovery table exists, and the table is not deleted. Just follow the procedure to update the data.
There is also a configuration, suitable for testing purposes, that is, <property name= "Hbm2ddl.auto" >create-drop</property>, so configured, that is, the initialization of the table (program startup), The table is deleted when the session factory (Sessionfactory) executes the Close method.
In addition, the last configuration of this property, that is, <property name= "Hbm2ddl.auto" >validator</property>, this configuration is generally not used in the development environment, Once hibernate discovers that the HBM mapping file is not the same as the table structure in the database, it throws an exception, and in development, the table structure is not arbitrarily changed, so this configuration is generally not used.
However: in general, in development, the general table structure we will be created in advance, usually using script commands to execute the script directly, so the so-called "lazy Building Table" method of the individual feel suitable for learning.
Persistent objects associated with the HBM mapping file:
The mapping file configures the correspondence between the object and the table, so hibernate is also required for persistent objects
1. Persistent objects must have no parameter constructor
For example: Querying the first user in the table, using the user object to receive data, user U = Session.get (user.class,1), then hibernate will help us create a user object by reflection and then plug the data into that object. So if the object does not have a parameterless constructor, hibernate will not be able to create an entity instance for us.
2. Provide an identity attribute (typically mapped as a table's primary key field)
3. Get/set method to provide attributes
Above 3 points is a must-do item * * *
4. You cannot set final for a persisted object, so that the object cannot be inherited, that is, the final class will affect Hibernate's lazy loading function, this follow-up said, but there is no need to set the object final
5. If you need to put the persisted object into the set, the persisted object needs to override the Equals and Hashcode methods when the associated mapping is required
2. Learn hibernate configuration file 1 with persistent object