gpt4 book ai didi

hibernate - Hibernate Stateless Session批量插入关联实例的有效方法

转载 作者:行者123 更新时间:2023-12-02 14:48:48 25 4
gpt4 key购买 nike

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

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!"
}
}

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

最佳答案

您可以尝试使用 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
希望它可以提供帮助。

关于hibernate - Hibernate Stateless Session批量插入关联实例的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47708299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com