【问题标题】:Hibernate: hbm2ddl.auto=update und autoincrement休眠:hbm2ddl.auto=update 和 autoincrement
【发布时间】:2011-12-09 06:05:22
【问题描述】:

如果 Table 没有 auto_increment,如果我尝试在 Table 中插入一些内容,则会抛出异常 «org.hibernate.HibernateException: The database returned no natively generated identity value»。 Id 被映射为:

    @Id @GeneratedValue
    private int id;

我虽然有 hbm2ddl.auto=update。不幸的是,它没有通过验证在目标表上设置 AUTO_INCREMENT。我可以实现它,没有 HQL,没有原生 SQL 更好?

【问题讨论】:

    标签: java hibernate auto-increment


    【解决方案1】:

    在 PostgreSQL 中,我发现了两种通过 hbm2ddl.auto=create 进行自动增量的方法

    1.

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Integer id;
    

    PostgreSQL 生成 PK 为id serial not null 即每个表的唯一序列

    2.

    @Id
    @Column(name = "id", unique = true, nullable = false, columnDefinition = "integer default nextval('hibernate_sequence')")
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    protected Integer id;
    

    在这种情况下,FK 发生了一些奇怪的事情:

    create table meals (
        id integer default nextval('hibernate_sequence') not null,
        calories int4 not null,
        date_time timestamp not null,
        description varchar(255) not null,
        user_id integer default nextval('hibernate_sequence') not null,
        primary key (id)
    )
    

    在 h2 中自动生成和自动增量工作正常。

    【讨论】:

      【解决方案2】:

      hbm2ddl 设置与身份GenerationType 无关。

      您可以编写自己的 ID/密钥生成器类,并让 hibernate 知道您自己的密钥生成器类。然后hibernate会从你自己的生成器中获取身份。

      一些你可能想看看的文章:

      http://blog.anorakgirl.co.uk/?p=43

      http://www.devx.com/Java/Article/30396/0/page/3

      Hibernate ID Generator

      对于生成 ID 的逻辑,这取决于您的要求。最简单的方法是 max(id)+1,您可以缓存 max(id) 以提高性能。好吧,如果您在集群环境中运行应用程序,则必须注意线程安全问题以及缓存同步问题。

      顺便说一句,你在玩哪个数据库?

      更新

      打开http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#mapping-declaration-id,然后搜索“5.1.2.2.1。各种其​​他生成器”看看,如果您的应用程序没有在集群中运行,请尝试生成类型“增量”。

      【讨论】:

      • >顺便说一句,你在玩哪个数据库? MySQL
      • 但我真的不想从自定义生成器开始,我只想让 Hibernate 使所有 ID 列 AUTO_INCREMENT,如果它们不是。有什么简单的方法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 2012-05-24
      • 2014-11-16
      • 2010-09-18
      相关资源
      最近更新 更多