Hibernate optimization: Mapping two properties to the same field

Recently spent some time optimizing code in our application.

One of the things I was trying to optimize is creating a pretty big graph of objects which has lots of fields. So lets say we have:

class User {

class Record {
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
User user;

The code is okay. But what if you’re trying to insert 10000 records for 10000 users at once. Well, the easy solution not to load all 10000 complex users is to use _session.load(User.class, id)_. So far so good. Using @Transactional annotation from Spring somehow tried to build proxy object hashCode in the aspect which forced data to be loaded from the database. So it’s still pretty slow.

But why not inserting the long user id right away if we already know it and still go without plain SQL?

class Record {
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", insertable = false, updatable = false)
User user;

@Column(name = "user_id")
Long userId;

This way you can create record object with the Long value of “user_id” only and still get the full-blown lazy User through User Record#getUser()

This entry was posted in Development, Tips and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s