问题描述
假设我有一个Car
实体:
@Entity
public class Car {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
当我向数据库添加新对象时,spring如何知道要自动增加什么值?
How does spring know what value to autoincrement when I add a new object to the database?
推荐答案
Here is a good explanation of primary keys generation strategies
如果使用Hibernate作为持久性提供程序,它将选择一个 基于数据库特定方言的生成策略.对于大多数 流行的数据库,它选择GenerationType.SEQUENCE .
If you use Hibernate as your persistence provider, it selects a generation strategy based on the database specific dialect. For most popular databases, it selects GenerationType.SEQUENCE.
GenerationType.IDENTITY是最容易的使用方式,但不是最好的一种 从性能的角度来看.它依靠自动递增 数据库列,并让数据库为每个数据库生成一个新值 插入操作.从数据库的角度来看,这是非常有效的,因为对自动增量列进行了高度优化,并且不需要任何其他语句.
The GenerationType.IDENTITY is the easiest to use but not the best one from a performance point of view. It relies on an auto-incremented database column and lets the database generate a new value with each insert operation. From a database point of view, this is very efficient because the auto-increment columns are highly optimized, and it doesn’t require any additional statements.
如果您使用Hibernate,则此方法存在明显的缺点. Hibernate要求每个受管实体都有一个主键值,并且 因此必须立即执行插入语句.这 阻止它使用其他优化技术(例如JDBC) 批处理.
This approach has a significant drawback if you use Hibernate. Hibernate requires a primary key value for each managed entity and therefore has to perform the insert statement immediately. This prevents it from using different optimization techniques like JDBC batching.
GenerationType.SEQUENCE使用数据库序列来生成 独特的价值观.它需要附加的select语句才能获得 数据库序列中的下一个值.但这没有表现 对大多数应用程序的影响.
The GenerationType.SEQUENCE uses a database sequence to generate unique values. It requires additional select statements to get the next value from a database sequence. But this has no performance impact for most applications.
如果您不提供任何其他信息,则Hibernate将 从其默认序列中请求下一个值.你可以改变 通过在生成器中引用@SequenceGenerator
的名称 @GeneratedValue
批注的属性. @SequenceGenerator
注释使您可以定义生成器的名称,名称和 数据库序列的模式和分配的大小 顺序.
If you don’t provide any additional information, Hibernate will request the next value from its default sequence. You can change that by referencing the name of a @SequenceGenerator
in the generator attribute of the @GeneratedValue
annotation. The @SequenceGenerator
annotation lets you define the name of the generator, the name, and schema of the database sequence and the allocation size of the sequence.
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@SequenceGenerator(name="car_generator", sequenceName = "car_seq", allocationSize=50)
private Long id;
(旁注:通常首选Long
作为ID,而不是Integer
,因此用完的可能性较小)
(Side note: Usually prefer Long
for ids instead of Integer
so you're less likely to run out)
这篇关于Spring GeneratedValue批注用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!