带有Grails的Hibernate和PostgreSQL

发布于 2021-02-01 12:40:59

有一种简单的方法可以将hibernate设置为对每个带有postgres的表使用不同的主键ID。我试图在数据源中使用postgres方言:

dialect = org.hibernate.dialect.PostgreSQLDialect 
or
dialect = net.sf.hibernate.dialect.PostgreSQLDialect

但这是行不通的。谢谢

关注者
0
被浏览
85
1 个回答
  • 面试哥
    面试哥 2021-02-01
    为面试而生,有面试问题,就找面试哥。

    简短的答案是没有,没有 简单的
    方法可以做到这一点。但是,我找到了一种有效的解决方案。基本上,您需要实现自定义方言。这是一个实现(请在注释中注明实现的原始来源)。

    package com.my.custom;
    
    import java.util.Properties;
    
    import org.hibernate.dialect.Dialect;
    import org.hibernate.dialect.PostgreSQLDialect;
    import org.hibernate.id.PersistentIdentifierGenerator;
    import org.hibernate.id.SequenceGenerator;
    import org.hibernate.type.Type;
    
    
    /**
     * Creates a sequence per table instead of the default behavior of one sequence.
     *
     * From <a href='http://www.hibernate.org/296.html'>http://www.hibernate.org/296.html</a>
     * @author Burt
     */
    public class TableNameSequencePostgresDialect extends PostgreSQLDialect {
    
        /**
         * Get the native identifier generator class.
         * @return TableNameSequenceGenerator.
         */
        @Override
        public Class<?> getNativeIdentifierGeneratorClass() {
                return TableNameSequenceGenerator.class;
        }
    
        /**
         * Creates a sequence per table instead of the default behavior of one sequence.
         */
        public static class TableNameSequenceGenerator
               extends SequenceGenerator {
    
                /**
                 * {@inheritDoc}
                 * If the parameters do not contain a {@link SequenceGenerator#SEQUENCE} name, we
                 * assign one based on the table name.
                 */
                @Override
                public void configure(
                                final Type type,
                                final Properties params,
                                final Dialect dialect) {
                        if (params.getProperty(SEQUENCE) == null
                                        || params.getProperty(SEQUENCE).length() == 0) {
                                String tableName = params.getProperty(PersistentIdentifierGenerator.TABLE);
                                if (tableName != null) {
                                        params.setProperty(SEQUENCE, "seq_" + tableName);
                                }
                        }
                        super.configure(type, params, dialect);
                }
        }
    
    }
    

    上述实施应当存储为TableNameSequencePostgresDialect.javasrc/java/com/my/custom你的Grails项目中。

    接下来,更新您的语言DataSource.groovy以使用此新的自定义方言。

    dialect = com.my.custom.TableNameSequencePostgresDialect
    

    差不多了。不 容易, 但是可以做到。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看