1

我正在尝试使用 Hibernate 无状态会话进行批量插入

class Book {
    String title;
    String author;
    Double price;
    Publisher publisher;

    static constraints = {
        publisher nullable: true
    }

    static mapping = {
        id generator: 'assigned'
    }
}


class Publisher {

    String name

    static hasMany = [book: Book] // add one line here

    static constraints = {

    }

    static mapping = {
        id generator: 'assigned'
    }
}

批量插入测试代码:

class BatchController {
    SessionFactory sessionFactory;

    def testBatchInsert() {
        StatelessSession session = sessionFactory.openStatelessSession()
        Transaction tx = session.beginTransaction();
        int count = 100;
        for (int i = 0; i < count; i++) {
            def publisher = ["publisher": (i % 1000)] // make publisher id
            //The above code have to load publisher from db, or "save the transient instance before flushing" exception will throw.
            Book book = new Book()
            bindData(book, publisher) // use data binding here to set publisher id for the instance
            book.setId(i)
            book.setTitle("title $i")
            book.setAuthor("author $i")
            book.setPrice(123.456)
            session.insert(book)
        }
        tx.commit()
        render "finished!"
    }
}

有什么方法可以跳过从数据库加载发布者并提高处理性能?(所有发布者都已存在于表中)。

4

1 回答 1

0

您可以尝试使用 bindData 如下

    StatelessSession session = sessionFactory.openStatelessSession()
    for (int i = 0; i < count; i++) {
        def publisher = ["publisher": (i % 1000)] // make publisher id
        //The above code have to load publisher from db, or "save the transient instance before flushing" exception will throw.
        Book book = new Book()
        bindData(book, publisher) // use data binding here to set publisher id for the instance
        book.setId(start + i)
        book.setTitle("title $i")
        book.setAuthor("author $i")
        book.setPrice(123.456) 
        session.insert(book)
    }

// 在域 publisher 中添加 publisher 和 book 之间的关系

class Publisher {

    String name

    static hasMany = [book: Book] // add one line here

    static constraints = {

    }

    static mapping = {
        id generator: 'assigned'
    }
}

参考:http
://docs.grails.org/latest/ref/Controllers/bindData.html 希望它可以提供帮助。

于 2017-12-08T10:27:10.837 回答