2
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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I guess there is no way to do this without an entityManager, I would love to fix this in a mapstruct converter without any knowledge of the database and have it hook up to database when the account is sent to create but I doubt that is possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.