我正在尝试使用 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!"
}
}
有什么方法可以跳过从数据库加载发布者并提高处理性能?(所有发布者都已存在于表中)。