Jeppz
Jeppz

Reputation: 982

Creating Hibernate proxy objects

public class Account {
    private int pk;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "profileFK")
    private Profile profile;
}

public class Profile {
    private int pk;
    private String name;
}

I have an account and a profilePk and I want to be able to set the relation without getting the profile from the database, is there a way to create a HibernateProxy when I have the PK for it?

I tried just making a new Profile with just the PK in it which works when saving to db but it also puts the "empty" object in the hibernate cache.

Profile dbProfile = new Profile();
dbProfile.setName("name");
profileDao.create(dbProfile);

Profile profile = new Profile();
profile.setPk(dbProfile.getPk());
account.setProfile(profile);
accountDao.save(account);

Account dbAccount = accountDao.get(account.getPk());
assertNull(dbAccount.getProfile().getName());
accountDao.refresh(dbAccount);
assertEquals("name", dbAccount.getProfile().getName());

But I want to do something like this

Profile dbProfile = new Profile();
dbProfile.setName("name");
profileDao.create(dbProfile);

account.setProfile(Hibernate.newProxy(Profile.class, dbProfile.getPk()));
accountDao.save(account);

Account dbAccount = accountDao.get(account.getPk());
assertEquals("name", dbAccount.getProfile().getName());

Or is there another option where I don't have to get the profile from DB before saving account? We are migrating hundreds of generated old objects with mapstruct to jpa and something like this would make a generic solution a lot easier.

Upvotes: 2

Views: 631

Answers (1)

SternK
SternK

Reputation: 13051

According to the hibernate documentation you should do something like this:

Profile dbProfile = new Profile();
dbProfile.setName("name");
profileDao.create(dbProfile);

account.setProfile(entityManager.getReference(Profile.class, dbProfile.getPk()));
accountDao.save(account);

Upvotes: 1

Related Questions