1. Mapping configuration in XML mode
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE hibernate-mapping public
'-//hibernate/hibernate mapping DTD 3.0//en '/
http Hibernate.sourceforge.net/hibernate-mapping-3.0.dtd ' >
At this point, the XML configuration is complete.
The Userdao.java code is as follows:
public class Userdao {public
void Saveuser (user user) {
sessionfactory SF = new Configuration (). Configure ()
. Buildsessionfactory ();
Session session = NULL;
Transaction Transaction = null;
try {
session = Sf.opensession ();
Transaction = Session.begintransaction ();
Session.save (user);
Transaction.commit ();
} catch (Hibernateexception e) {
transaction.rollback ();
E.printstacktrace ();
} finally {
session.close ();}}
}
It can be used after testing.
2, the annotation way to map the configuration
① adds the following attributes to the Hibernate.cfg.xml session-factory:
<mapping class= "Com.hsb.hibernate.entity.User"/>
Attention differs from the first way, class and resource
② adding various annotations to the entity class
@Entity
@Table (name = "Tab_user") public
class User {
@Id
@GenericGenerator (name = "Generator", Strategy = "increment")
@GeneratedValue (generator = "generator")
@Column (name = "UUID")
private int uuid;< c7/> @Column (name = "userid")
private String userid;
@Column (name = "name")
private String name;
@Column (name = ' age ')
private int age;
public int Getuuid () {
return uuid;
}
public void Setuuid (int uuid) {
this.uuid = uuid;
}
Public String getUserId () {
return userId;
}
public void Setuserid (String userId) {
This.userid = userId;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
this.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
this.age = age;
}
}
Note: The type in the entity class should match the type of the field in the database. Field names in the database should try to avoid uppercase letters, if there are uppercase letters in the field name, the insert or update fails, and the hint field does not exist. The annotation method does not need to associate the entity class and the data table in the XML file, but instead uses the annotation in the entity class.
The following points should be noted when using annotations:
A, if the entity class attribute name is inconsistent with the table field name, either the annotation is before the property or both are annotated before the Get method. cannot be partially annotated before the attribute, some annotations before the method.
B, if the entity class attribute name is consistent with the table field name, it can be partially annotated before the attribute, some annotations before the method.
c, if some attributes in the entity class are not annotated: (Attributes and get do not write annotations), the default is that the table field name is the same as the entity class property name.
D, if a member attribute of the entity class does not need to be stored in the database, use @transient to annotate it. (Some fields in the XML configuration are not written and do not need to be mapped for this member property)
E, the table name can be annotated before the entity class.
F, all these annotations are under: Javax.persistence package. Not in a hibernate package.
At this point, the annotation mode mapping configuration is complete.
The Userdao.java code is as follows:
public class Userdao {public
void Saveuser (user user) {
sessionfactory sessionfactory = new Annotationconfigurat Ion ()
. Configure (). Buildsessionfactory ();
Session session = NULL;
Transaction Transaction = null;
try {
session = Sessionfactory.opensession ();
Transaction = Session.begintransaction ();
Session.save (user);
Transaction.commit ();
} catch (Hibernateexception e) {
transaction.rollback ();
E.printstacktrace ();
} finally {
session.close ();}}
}
Tested and available.
Note: In Hibernate 3.6, "org.hibernate.cfg.AnnotationConfiguration" are deprecated, and all its functionality have been moved to "Org.hibernate.cfg.Configuration". So, you can safely replace your "annotationconfiguration" with "Configuration" class.
Buildsessionfactory API has been deprecated, and it's easy-to-do well. You can use Standardserviceregistrybuilder, because Serviceregistrybuilder also have been deprecated.
Configuration configuration = new configuration ();
Configuration.configure ();
Standardserviceregistrybuilder builder = new Standardserviceregistrybuilder ()
. Applysettings ( Configuration.getproperties ());
Sessionfactory sessionfactory = Configuration
. Buildsessionfactory (Builder.build ());
The difference between the two approaches is obvious, but it's easy to overlook if you're not careful, especially when it comes to getting started. Annotations are clearly more suitable for large projects and easier to use and manage than the way XML is configured. In addition, the notation is introduced in hibernate4, and if you want to use this approach in hibernate3, you need to introduce a hibernate-annotation package.
Reference article:
Http://www.cnblogs.com/xiaoluo501395377/p/3374955.html
Report:
hibernate various primary key generation strategies and configuration detailed transferred from: http://www.cnblogs.com/kakafra/archive/2012/09/16/2687569.html 1, assigned
The primary key is generated by an external program and must be specified before save (). Hibernate is not responsible for maintaining primary key generation. It is independent of hibernate and the underlying database, and can be cross-database. Before storing the object, it is necessary to use the setter method of the primary key to assign a value to the primary key, and as to how this value is generated, it is entirely up to you to avoid this method.
<id name= "id" column= "id" >
<generator class= "Assigned"/>
</id>
"UD" is a custom policy name, with an artificially named name, followed by "UD".
features: Can be cross-database, human control of primary key generation, should be avoided as far as possible. 2, Increment
The maximum value of the primary key is fetched from the database by hibernate (only 1 times per session), based on that value, each increment is 1, the primary key is generated in memory and is not dependent on the underlying database, so it can cross the database.
<id name= "id" column= "id" >
<generator class= "increment"/>
</id>
Hibernate calls the Generate () method inside the Org.hibernate.id.IncrementGenerator class, using the Select Max (idcolumnname) from TableName statement to get the primary key maximum value. This method is declared as synchronized, so there is no problem inside a standalone Java virtual machine, however, the same value may be fetched when multiple JVMs concurrently access the database select Max, and then insert occurs dumplicate Entry's error. So there can only be one hibernate application process to access the database, otherwise it may produce primary key conflicts, so it is not suitable for multi-process concurrent update database, suitable for a single process to access the database, not for the cluster environment.
Official documents: Use only when no other process is inserting data into the same table, not in the cluster.
Features: Cross-database, not suitable for multi-process concurrent update database, suitable for a single process to access the database, not for the cluster environment. 3. Hilo
Hilo (High and low) is the most common form of production in Hibernate and requires an extra table to hold the value of hi. The table that holds the HI value has at least one record (only related to the first record), or an error occurs. can span databases.
<id name= "id" column= "id" >
<generator class= "Hilo" >
<param name= "table" >hibernate_hilo</param>
<param name= "column" >next_hi</param>
<param name= "Max_lo" >100</param>
</generator>
</id>
<param name= "table" >hibernate_hilo</param> Specifies the name of the table that holds the HI value
<param name= "column" >next_hi</param> Specify column names to hold hi values
<param name= "Max_lo" >100</param> Specify the maximum value of the low
You can also omit the table and column configurations, whose default table is Hibernate_unique_key, which is listed as Next_hi
<id name= "id" column= "id" >
<generator class= "Hilo" >
<param name= "Max_lo" >100</param>
</generator>
</id>
The Hilo generator process for generating a primary key (in the Hibernate_unique_key table, next_hi column example):
1. Get Hi Value: Reads and records the value of the Next_hi field in the database's Hibernate_unique_key table, and the value of this field in the database is saved by 1.
2. Obtain the LO value: from 0 to Max_lo Loop, the difference is 1, the value is Max_lo, and then the LO value continues from 0 to Max_lo Loop.
3. Generate the primary key value according to the formula Hi * (Max_lo + 1) + lo calculation.
Note: When the Hi value is 0, then the first value is not 0* (max_lo+1) +0=0, but Lo skips 0 starting from 1, directly 1, 2, 3 ...
That Max_lo configuration how much suitable for it.
This depends on the situation, if the system generally does not restart, and the need to use this table to establish a large number of primary keys, you can max_lo configuration larger, so you can reduce the number of reading data tables, improve efficiency; Conversely, if the server is often restarted, you can max_lo a smaller configuration, You can avoid a large interval between each reboot of the primary key, which causes the primary key value of the primary key to be incoherent.
Features: Cross-database, the flags generated by the Hilo algorithm are guaranteed to be unique only in one database. 4, Seqhilo
Similar to Hilo, the primary key generation mechanism implemented by the HI/LO algorithm simply replaced the data table in Hilo with the sequence sequence, requiring the database to first create sequence for sequence-enabled databases, such as Oracle.
<id name= "id" column= "id" >
<generator class= "Seqhilo" >
<param name= "sequence" >hibernate_seq</param>
<param name= "Max_lo" >100</param>
</generator>
</id>
feature: Similar to Hilo, it can only be used in a database that supports sequences. 5, Sequence
Using the sequence mechanism provided by the database to generate the primary key requires the database to support sequence. Sequence in Oralce, DB, SAP db, Postgersql, Mckoi. MySQL does not support the sequence database (you can use identity).
<generator class= "sequence" >
<param name= "sequence" >hibernate_id</param>
</generator>
<param name= "sequence" >hibernate_id</param> Specify the name of the sequence
When hibernate generates a primary key, it looks for sequence and assigns it to the primary key value, the primary key value is generated by the database, hibernate is not responsible for maintenance, and you must first create a sequence if you do not specify the sequence name. Use Hibernate's default sequence, named Hibernate_sequence, if you want to create the sequence in the database.
features: Can only be used in a database that supports sequences, such as Oracle. 6. Identity
The identity is generated by the underlying database identifier. The identity is generated by the database itself, but the primary key must be set to self-grow, using identity as a precondition for the underlying database to support autogrow field types such as DB2, SQL Server, MySQL, Sybase, and Hypersonicsql, etc. Oracle does not support this type of field without self-increment.
<id name= "id" column= "id" >
<generator class= "Identity"/>
</id>
Example: If you use a MySQL database, the primary key field must be set to Auto_increment.
ID Int (one) primary key auto_increment
Features: Use only in field databases that support autogrow, such as MySQL. 7, native
Native by hibernate according to the database used by the use of identity, Hilo, sequence one of the primary key generation mode, flexibility is strong. If the identity is supported, the identity is used and sequence is used if sequence is supported.
<id name= "id" column= "id" >
<generator class= "native"/>
</id>
For example, MySQL uses identity,oracle to use sequence
Note: If hibernate automatically selects sequence or Hilo, all table primary keys will be taken from Hibernate's default sequence or Hilo table. Also, some databases are not very efficient in support of the default primary key generation test.
When using sequence or Hilo, you can add parameters, specify sequence names or Hi-value table names, and so on, such as
<param name= "sequence" >hibernate_id</param>
Features: According to the automatic selection of the database, if you use multiple databases in the project, you can use this method, you need to set the table's self-increment field or set up a sequence, establish a table, etc. 8. UUID
uuid:universally unique Identifier, refers to the number generated on a machine, which guarantees that all machines in the same time and space are unique. Based on the standard calculations developed by the Open Software Foundation (OSF), the Ethernet card address, nanosecond time, chip ID code and many possible numbers are used, the standard UUID format is:
xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx (8-4-4-4-12)
where each x is a hexadecimal number in the range of 0-9 or a-f.