如何在gorm-standalone / grails上使用TableGenerator策略

时间:2018-01-15 18:52:49

标签: spring-boot grails gorm

出于遗留兼容性原因,我尝试在gorm-standalone 5或grails 3.1.16上应用逻辑以下代码

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "book_generator")
@TableGenerator(name="book_generator", table="id_generator", schema="bookstore")
@Column(name = "id", updatable = false, nullable = false)
private Long id;

以下代码是我正在努力的代码

package helloworld

class Book {

    Integer id
    String name
    String author

    static constraints = {
        id column: 'book_id'
        name blank: false
    }
    static mapping = {
        table 'BOOKTABLE'
        version false
        // id( generator: 'hilo', params: [table: 'BOOK_SEQ', column: 'next_value', max_lo: 1, initial_value: 1, increment_size: 1 ])
        id( generator: 'table', strategy: 'enhanced-table', parameters: [name: 'table_name', value: 'BOOK_SEQ', column: 'next_value', initial_value: 1, increment_size: 1 ])

    }
}

有可能吗?怎么样?

谢谢

1 个答案:

答案 0 :(得分:0)

实现你在Grails 3.1.16中尝试做的事情(使用hibernate4或hibernate5)。首先,通过添加到application.yml文件确保在启动时创建架构。

#Add this to any sample apps if you want the schema

environments:
    development:
        dataSource:
            dbCreate: create-drop
            url: jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS bookstore

然后您的域类应如下所示。

// Works in Grails 3.1.16 with Hibernate4 or Hibernate5

class BookGormTableSequence {

    String name
    String author

    static mapping = {
        version false
        id column: "book_id",
                generator: "enhanced-table",
                params: [schema: "BOOKSTORE", table_name: "BOOK_SEQ", initial_value: 300]
    }
}

如果您只想使用应提供更好性能的序列,则可以执行以下操作

//Works in Grails 3.1.16, 3.2.x, and 3.3.x

class BookGormSequence {

    String name
    String author

    static mapping = {
        version false
        id column: "book_id", generator: "sequence", params: [sequence_name: "bookGormseq", initial_value: 200]
    }
}

向前移至Grails 3.2+,Gorm 6.0或6.1不再支持generator: "enhanced-table"。 "序列"生成器将适用于所有测试版本。一旦Gorm 6.1.x可用,JPA Mapping就是supported。这意味着您的原始语法几乎不会修改。

// Table Sequence as in your question
import javax.persistence.*

@Entity
class BookJpaTableSequence {

    @Id
    @TableGenerator(name="book_generator", table="BOOK_SEQ", schema="bookstore", initialValue = 55)
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "book_generator")
    @Column(name = "book_id", updatable = false, nullable = false)
    Long id
    String name
    String author
}

使用JPA注释的正常序列

// Normal Sequence - Should be more performant.
import javax.persistence.*

@Entity
class BookJpaSequence {

    @Id
    @SequenceGenerator(name = "book_generator", sequenceName = "bookJpaSeq", initialValue = 500)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_generator")
    @Column(name = "book_id", updatable = false, nullable = false)
    Long id
    String name
    String author
}