一、简介

1.You now have three methods for distinguishing references:

 Objects are identical if they occupy the same memory location in the JVM . This can be checked with the a == b operator. This concept is known as object identity.
 Objects are equal if they have the same state, as defined by the a.equals(Object b) method. Classes that don’t explicitly override this method inherit the implementation defined by java.lang.Object , which compares object identity with == . This concept is known as object equality.
 Objects stored in a relational database are identical if they share the same table and primary key value. This concept, mapped into the Java space, is known as database identity.

2.To become the primary key, a candidate key must satisfy the following requirements:

 The value of any candidate key column is never null. You can’t identify something with data that is unknown, and there are no nulls in the relational model.Some SQL products allow defining (composite) primary keys with nullable columns, so you must be careful.
 The value of the candidate key column(s) is a unique value for any row.
 The value of the candidate key column(s) never changes; it’s immutable.

3.JPA标准支持的生id成策略

Usually you want the system to generate a primary key value when you save an entity instance, so you write the @GeneratedValue annotation next to @Id . JPA standardizes several value-generation strategies with the  javax.persistence.GenerationType enum, which you select with @GeneratedValue(strategy = ...) :
 GenerationType.AUTO —Hibernate picks an appropriate strategy, asking the SQL dialect of your configured database what is best. This is equivalent to @GeneratedValue() without any settings.
 GenerationType.SEQUENCE —Hibernate expects (and creates, if you use the tools) a sequence named HIBERNATE_SEQUENCE in your database. The sequence will be called separately before every INSERT , producing sequential numeric values.
 GenerationType.IDENTITY —Hibernate expects (and creates in table DDL ) a special auto-incremented primary key column that automatically generates a numeric value on INSERT , in the database.
 GenerationType.TABLE —Hibernate will use an extra table in your database schema that holds the next numeric primary key value, one row for each entity class. This table will be read and updated accordingly, before INSERT s. The default table name is HIBERNATE_SEQUENCES with columns SEQUENCE_NAME and SEQUENCE_NEXT_HI_VALUE . (The internal implementation uses a more complex but efficient hi/lo generation algorithm; more on this later.)

4.用生成器生成id

JPA has two built-in annotations you can use to configure named generators: @javax .persistence.SequenceGenerator and @javax.persistence.TableGenerator .但Hibernate的更灵活,可以把生成器定义在与domainpackage-info.java文件中,且支持所有Hibernate提供的功能,可以自定义sequence表名,初始化值等。you can use the Hibernate annotation in a package-info.java file, typically in the same package as your domain model classes.Hibernate支持的生成器如下:

(1)native —Automatically selects other strategies, such as sequence or identity ,depending on the configured SQL dialect.

(2)sequence —Uses a native database sequence named  HIBERNATE_SEQUENCE .( org.hibernate.id.SequenceGenerator .)

(3)sequence-identity —Generates key values by calling a database sequence on insertion: for example, insert into ITEM(ID) values (HIBERNATE_SEQUENCE.nextval) .(org.hibernate.id.SequenceIdentityGenerator)

(4)enhanced-sequence —Uses a native database sequence when supported; otherwise falls back to an extra database table with a single column and row, emulating a sequence. Defaults to name HIBERNATE_SEQUENCE

,most likely your best option of the built-in strategies.( org.hibernate.id.enhanced.SequenceStyleGenerator )

(5)seqhilo —Uses a native database sequence named HIBERNATE_SEQUENCE , optimizing calls before INSERT by combining hi/lo values.(org.hibernate.id.SequenceHiLoGenerator)

(6)hilo —Uses an extra table named HIBERNATE_UNIQUE_KEY with the same algorithm as the seqhilo strategy.( org.hibernate.id.TableHiLoGenerator)

(7)enhanced-table —Uses an extra table named HIBERNATE_SEQUENCES , with one row by default representing the sequence, storing the next value.( org.hibernate.id.enhanced.TableGenerator )

(8)identity —Supports IDENTITY and auto-increment columns in DB2 , MySQL,MS SQL Server, and Sybase.

(9)increment —At Hibernate startup, reads the maximum (numeric) primary key column value of each entity’s table and increments the value by one each time a new row is inserted.

(10)select —Hibernate won’t generate a key value or include the primary key column in an INSERT statement. Hibernate expects the DBMS to assign a (default in schema or by trigger) value to the column on insertion. Hibernate then retrieves the primary key column with a SELECT query after insertion.

(11)uuid2 —Produces a unique 128-bit UUID in the application layer. Useful when you need globally unique identifiers across databases( org.hibernate.id.UUIDGenerator)

(12)guid —Uses a globally unique identifier produced by the database, with an SQL function available on Oracle, Ingres, MS SQL Server, and MySQL. Hibernate calls the database function before an INSERT .(  org.hibernate.id.IdentityGenerator)

总结:最好用pre-insert generation strategies,最好用enhanced-sequence

二、代码

1.结构

2.实体类

(1)

 package org.jpwh.model.simple;

 import javax.persistence.Entity;

 import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import javax.persistence.Version;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size; import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set; @Entity
public class Item { @Id
@GeneratedValue(generator = "ID_GENERATOR")
protected Long id; public Long getId() { // Optional but useful
return id;
} @Version
protected long version; @NotNull
@Size(
min = 2,
max = 255,
message = "Name is required, maximum 255 characters."
)
protected String name; @Future
protected Date auctionEnd; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Date getAuctionEnd() {
return auctionEnd;
} public void setAuctionEnd(Date auctionEnd) {
this.auctionEnd = auctionEnd;
} protected BigDecimal buyNowPrice; public BigDecimal getBuyNowPrice() {
return buyNowPrice;
} public void setBuyNowPrice(BigDecimal buyNowPrice) {
this.buyNowPrice = buyNowPrice;
} @Transient
protected Set<Bid> bids = new HashSet<Bid>(); public Set<Bid> getBids() {
return bids;
} public void setBids(Set<Bid> bids) {
this.bids = bids;
} @ManyToOne(fetch = FetchType.LAZY)
protected Category category; public Category getCategory() {
return category;
} public void setCategory(Category category) {
this.category = category;
} public void addBid(Bid bid) {
// Be defensive
if (bid == null)
throw new NullPointerException("Can't add null Bid");
if (bid.getItem() != null)
throw new IllegalStateException("Bid is already assigned to an Item"); getBids().add(bid);
bid.setItem(this);
} public Bid placeBid(Bid currentHighestBid, BigDecimal bidAmount) {
if (currentHighestBid == null ||
bidAmount.compareTo(currentHighestBid.getAmount()) > 0) {
return new Bid(bidAmount, this);
}
return null;
}
}

3.辅助类

(1)

 package org.jpwh.model;

 public interface Constants {

     // These are not used in the simple.Item class and in the model/package-info.java,
// as this would only confuse new users even more. So don't forget to rename them
// there if you rename them here.
public static final String ID_GENERATOR = "ID_GENERATOR";
public static final String ID_GENERATOR_POOLED = "ID_GENERATOR_POOLED"; }

(2)package-info.java

 @org.hibernate.annotations.GenericGenerator(
name = "ID_GENERATOR",
strategy = "enhanced-sequence",
parameters = {
@org.hibernate.annotations.Parameter(
name = "sequence_name",
value = "JPWH_SEQUENCE"
),
@org.hibernate.annotations.Parameter(
name = "initial_value",
value = "1000"
)
})
package org.jpwh.model;

JavaPersistenceWithHibernate第二版笔记-第四章-Mapping persistent classes-002identity详解的更多相关文章

  1. JavaPersistenceWithHibernate第二版笔记-第四章-Mapping persistent classes-003映射实体时的可选操作(<delimited-identifiers/>、PhysicalNamingStrategy、PhysicalNamingStrategyStandardImpl、、、)

    一.自定义映射的表名 1. @Entity @Table(name = "USERS") public class User implements Serializable { / ...

  2. JavaPersistenceWithHibernate第二版笔记-第四章-Mapping persistent classes-001区分entities and value types

    一.介绍 1.这种引用方式不对,但删除时不能级联 要这种引用方式 2.The Bid class could be a problem. In object-oriented modeling, th ...

  3. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-001Mapping basic properties(@Basic、@Access、access="noop"、@Formula、@ColumnTransformer、@Generated、 @ColumnDefaul、@Temporal、@Enumerated)

    一.简介 在JPA中,默认所有属性都会persist,属性要属于以下3种情况,Hibernate在启动时会报错 1.java基本类型或包装类 2.有注解 @Embedded 3.有实现java.io. ...

  4. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-006Mixing inheritance strategies(@SecondaryTable、@PrimaryKeyJoinColumn、<join fetch="select">)

    一.结构 For example, you can map a class hierarchy to a single table, but, for a particular subclass, s ...

  5. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-003Table per concrete class with unions(@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)、<union-subclass>)

    一.代码 1. package org.jpwh.model.inheritance.tableperclass; import org.jpwh.model.Constants; import ja ...

  6. JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-002Table per concrete class with implicit polymorphism(@MappedSuperclass、@AttributeOverride)

    一.结构 二.代码 1. package org.jpwh.model.inheritance.mappedsuperclass; import javax.persistence.MappedSup ...

  7. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-007UserTypes的用法(@org.hibernate.annotations.Type、@org.hibernate.annotations.TypeDefs、CompositeUserType、DynamicParameterizedType、、、)

    一.结构 二.Hibernate支持的UserTypes接口  UserType —You can transform values by interacting with the plain JD ...

  8. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-006类型转换器( @Converter(autoApply = true) 、type="converter:qualified.ConverterName" )

    一.结构 二.代码 1. package org.jpwh.model.advanced; import java.io.Serializable; import java.math.BigDecim ...

  9. JavaPersistenceWithHibernate第二版笔记-第五章-Mapping value types-005控制类型映射(Nationalized、@LOB、@org.hibernate.annotations.Type)

    一.简介 1. 2. 3. 4. to override this default mapping. The JPA specification has a convenient shortcut a ...

随机推荐

  1. sql总结

    sql总结 sql总结 where字句中使用的运算符 定义外键 定义主键 多表联合查询 统计函数 数据类型 sql语句格式 转换函数 null函数 运算符 日期 求某天是星期几 日期天数差 next_ ...

  2. SDOI2016 round1滚粗记

    Day -1 刚刚从HN集训回来,感觉整个人萌萌哒.考前不断立flag——这次我一定会滚粗的,然后设想着滚粗之后文化课先补什么,浑浑噩噩的过了一天,晚上看到CA爷(娘)发了关于cena爆栈的问题,这时 ...

  3. sql优化点整理

    此文是我最早开始sql优化至今整理的小知识点和经常遇到的问题,弄懂这些对优化大型的sql会有不少帮助 ---------------------------------使用了多余的外连接------- ...

  4. 四则运算2扩展---c++

    题目:让程序能接受用户输入答案,并判定对错.最后给出总共对/错 的数量. 一.设计思想 1.存储用户输入答案,与正确答案比较得出总共对错数量. 二.源程序代码 #include<iostream ...

  5. 我给女朋友讲编程html系列(4) -- html常用简单标签

    今天似乎有点感冒,浑身无力,在操场上躺了半个小时,好了许多.好了,废话不说了,还是写今天的教程吧. 1,html中的换行标签是 br,写法是: <br /> 2,html中有一些特殊的字符 ...

  6. Netsharp快速入门(之11) 销售管理(开发销售订单工作区)

    作者:秋时 杨昶   时间:2014-02-15  转载须说明出处 4.3     销售订单开发 4.3.1  部件工作区设置 1.创建部件工作区,建工作区向导中要注意勾选组合并系部分.具体要建立的部 ...

  7. Java 7 中 NIO.2 的使用——第二节 元数据文件的属性

    如果你有很多疑问关于一个文件或目录,它是否是隐藏的,它的大小是多少,谁拥有它,你可以从元数据中得到这些信息.所谓的元数据,就是描述数据的数据. NIO.2组织了这些原数据的属性的概念,并提供了java ...

  8. 802.11 wireless 七

    802.11 wireless 7Wireless Fundamentals : End-to-End Discovering the NetworkGetting Connect Clients i ...

  9. 02.Hibernate映射基础

    前言:Hibernate的核心功能是根据数据库到实体类的映射,自动从数据库绑定数据到实体类.使我们操作实体类(Java对象)就能对数据库进行增.删.查.改,而不用调用JDBC API使数据操作变得简单 ...

  10. boost之thread

    1.boost里的thread创建之后会立即启动. 代码示例: #include <iostream> #include <string> #include <vecto ...