SQL for Hibernate 4和5中序列的差异

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL for Hibernate 4和5中序列的差异相关的知识,希望对你有一定的参考价值。

有没有办法管理或更改Hibernate 5生成的sql,以了解如何从AS400 DB2中恢复序列?或者还原它使用Hibernate 4 SQL?

我有一个实体映射如下:

@Id
@Column(name = "D")
@SequenceGenerator(
        name = "art_id_gen",
        sequenceName = "G_ID_SEQ",
        allocationSize = 1)
@GeneratedValue(generator = "art_id_gen", strategy = GenerationType.SEQUENCE)
private long id;

当我使用Hibernate 4时,SQL是(可行的):

values nextval for G_ID_SEQ;

但是当使用Hibernate 5时,SQL是(它不起作用):

select next_val as id_val from G_ID_SEQ for update with rs;

我正在使用org.hibernate.dialect.DB2400Dialect

任何人都有一些输入或建议如何解决这个问题?

答案

解决方案是使用:

org.hibernate.dialect.DB2Dialect

这与hibernate 4生成相同的sql:

values
    nextval for G_ID_SEQ

一年后,我在我的代码中偶然发现了这一点,最终我们修补了DB2400Dialect:

/**
 * This is a patched version of the PatchedDB2400Dialect which is working in hibernate 5 and DB2 AS400
 *
 * There seems to be a problem with generated SQL for sequences and tables generated SQL for increment of unique id's
 * and identities. Either the sequence work when using DB2Dialect and not table generators or vice versa for DB2400Dialect.
**/
public class PatchedDB2400Dialect extends DB2400Dialect {
        private static final LimitHandler LIMIT_HANDLER = new AbstractLimitHandler() {
            @Override
            public String processSql(String sql, RowSelection selection) {
                if ( LimitHelper.hasFirstRow( selection ) ) {
                    //nest the main query in an outer select
                    return "select * from ( select inner2_.*, rownumber() over(order by order of inner2_) as rownumber_ from ( "
                            + sql + " fetch first " + getMaxOrLimit( selection ) + " rows only ) as inner2_ ) as inner1_ where rownumber_ > "
                            + selection.getFirstRow() + " order by rownumber_";
                }
                return sql + " fetch first " + getMaxOrLimit( selection ) + " rows only";
            }
...

以上是关于SQL for Hibernate 4和5中序列的差异的主要内容,如果未能解决你的问题,请参考以下文章

5 -- Hibernate的基本用法 --4 4 数据库方言

Hibernate--SQL

4. Hibernate检索方式

hibernate基础

Hibernate 5 ID AUTO 生成类型为 Oracle 作为序列和 MySQL 作为身份

得到错误 org.h2.jdbc.JdbcSQLSyntaxErrorException:找不到序列“HIBERNATE_SEQUENCE”; SQL 语句: