ORM: OneToOne mapping on Non Primary-Key Join column - Book and Inventory mapped by ISBN

Sathish picture Sathish · Mar 22, 2009 · Viewed 14.6k times · Source

I have a Book model and Inventory model mapped by ISBN number, but ISBN is not the primary key in either. Books belong to Bookstores and Inventory is for a group of Bookstores(BookstoreChain). Inventory is shared by all Bookstores belonging to a BookstoreChain.

I'm using Hibernate @OneToOne mapping on the book side to fetch inventory info by joining the ISBN column. Somehow, Hibernate generates the left outer join query correctly, but inventory is null on the Book object. Its not lazy loaded either. Ignoring the Bookstore and Chain, how do i do a OneToOne or ManyToOne join and fetch inventory when Books are fetched?

class Book{
@Id
Long id

@Column
String isbn;

@Column
String title;

@OneToOne(optional = true)
@JoinColumn(name = "isbn", referencedColumnName = "isbn",insertable = false, updatable = false)
Inventory inventory;
}

class Inventory{
@Id
Long id

@Column
String chainId

@Column
String isbn

@Column
Long availableQty
}

Answer

Jesse picture Jesse · Jun 15, 2009

You have to name your join reference something else. isbn is already a column. Try this:

@OneToOne(optional = true)
@JoinColumn(name = "inventory", referencedColumnName = "isbn",insertable = false, updatable = false)
Inventory inventory;