Distinguish between two data in the database is the same bar, by the primary key PK
In the JVM, there is a memory area called Hibernate memory, in the JVM and hibernate memory can have multiple identical objects, distinguish whether two objects are the same object by the address (the Equals method in object, What do you rely on in hibernate memory?
OID Object Unique Identifier
OID usage principles: Let hibernate use the database to maintain the ability to
The primary key types defined in Hibernate are: Natural primary key and proxy primary key:
Natural PRIMARY Key: Has the business meaning field as the primary key, for example: study number, XXX number
Surrogate PRIMARY Key: does not have a business meaning field as a primary key (for example, a self-increment ID), such as: MySQL self-increment primary key, the unique sequence string generated by the Oracle sequence-generated primary key, UUID () method
I generally use the proxy primary key
The primary key generation policy that can be set in Hbm.xml is as follows:
increment 代理主键。 由hibernate维护一个变量,每次生成主键时自动以递增。 问题:如果有多个应用访问一个数据库,由于每个应用维护自己的主键,所以此时主键可能冲突。建议不采用。 hibernate会先去数据库查询主键是多少,然后再自增,然后给实体类赋值,在去插入,这样就会有线程安全问题,如果两个人在同时插入数据,那么很有可能,有一个人插入失败
identity 代理主键。 由底层数据库生成表识符。条件是数据库支持自动增长数据类型。比如:mysql的自增主键,oracle不支持主键自动生成。如果数据库支持自增建议采用。
sequence 代理主键。 Hibernate根据底层数据库序列生成标识符。条件是数据库支持序列。比如oracle的序列。如果数据库支持序列建议采用。
native 代理主键。 根据底层数据库对自动来选择identity、sequence、hilo 由于生成主键策略的控制权由hibernate控制,所以不建议采用。
uuid 代理主键。 Hibernate采用128位的UUID算法来生成标识符。该算法能够在网络环境中生成唯一的字符串标识符。此策略可以保证生成主键的唯一性,并且提供了最好的数据库插入性能和数据库平台的无关性。建议采用。
assigned 自然主键。 由java程序负责生成标识符。不建议采用。
hilo 代理主键。 使用高低位算法生成主键。必须是long、int、short类型。该算法生成的标识符只能在一个数据库中保证唯一。
How hibernate distinguishes between two objects is not the same