Hibernate:概述了@GeneratedValue的工作原理 [英] Hibernate: rundown on how @GeneratedValue works

查看:429
本文介绍了Hibernate:概述了@GeneratedValue的工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



数据库总是会被查询并返回最后一个值?如果两个不同的进程(不同的Hibernate应用程序)同时访问同一个表,会发生什么情况?特别是使用自动数字值和序列时,会发生什么? 解决方案

我假定您正在引用JPA @GeneratedValue。



@GeneratedValue 注释告诉ORM如何计算出该字段的价值。



例如:

  @Id 
@GeneratedValue(strategy = SEQUENCE,generator =CUST_SEQ)
@Column(name =CUST_ID)
public Long getId(){return id; }

例子2:

@Id
@GeneratedValue(strategy = TABLE,generator =CUST_GEN)
@Column(name =CUST_ID )
长ID;

要理解的关键是生成的值有一个策略,生成的值的策略决定怎么了。在上面的例子中,SEQUENCE生成策略意味着当首次保存对象时,ORM将向数据库询问序列的新值。第二个示例指定了表生成策略,这意味着ORM将查询表中的行以确定id的值。在示例2中,使用哪个表的详细信息不会显示,因为它引用了一个名为CUST_GEN的生成器。您将遇到的Typcial生成器。


  • 身份 - 在插入问自动incerement列以获取物品的价值

  • 序列 - 值来自数据库序列

  • 表 - 该值来自数据库中的另一个表

  • auto - 根据数据库类型
  • UUID - 在执行插入操作之前生成一个UUID


    有可能开发定制发电机。与数据库的交互取决于生成策略。

    I am having troubling finding an accurate explanation of @GeneratedValue and the different strategies regarding on what happens from a database point of view.

    Will the database always be queried and the last value available returned? what happens if 2 different process (different Hibernate apps) access to the same table at the same time?specifically with auto numeric values and sequences

    解决方案

    I am assuming you are refering to the JPA @GeneratedValue.

    The @GeneratedValue annotation tells the ORM how to figure out the value of that field.

    For example:

     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ")
     @Column(name="CUST_ID")
     public Long getId() { return id; }
    
     Example 2:
    
     @Id
     @GeneratedValue(strategy=TABLE, generator="CUST_GEN")
     @Column(name="CUST_ID")
     Long id;
    

    The key thing to understand is that a generated value has a strategy and the strategy of the generated value determines what happens. In the above example the SEQUENCE generation strategy means that the ORM will ask the database for a new value for the sequence when saving an object for the first time. The second example specify a table generation strategy which means that the ORM will consult a row in a table to determine the value of a id. In example example 2 the details of which table is used are not show since it reference a generator called "CUST_GEN"

    Typcial generators you will run into.

    • Identity - After an insert ask the auto incerement column for the value of the item
    • Sequence - the value comes from a db sequence
    • table - the value comes from another table in the database
    • auto - pick one of the above based on the database type
    • UUID - generate a UUID before doing an insert

    It is possible to develop custom generator. The interaction with the database will depend on generation strategy.

    这篇关于Hibernate:概述了@GeneratedValue的工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆