I am trying to use Hibernate stateless session to do batch insertion
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'
}
}
The batch inserting test code:
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!"
}
}
Any way to skip loading publisher from db and improve the processing performance? (All publishers exist in the table already).