user2994883
user2994883

Reputation: 44

Relationship mapping in Hibernate Java - save owning side entity

I have 2 tables

I'm trying to create a relationship between said 2 tables. A user can have many urls, but a url can belong to only one user.

This sounds to me like a OneToMany relationship.

My User Entity is as follows(some code was removed as to not make it too long):

public class User{

    @OneToMany(
            mappedBy = "user",
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private final List<RssUrl> rssUrls = new ArrayList<>();

    public void addRssUrl(RssUrl rssUrl) {
        rssUrls.add(rssUrl);
        rssUrl.setUser(this);
    }

    public void removeComment(RssUrl rssUrl) {
        rssUrls.remove(rssUrl);
        rssUrl.setUser(null);
    }

My Url Entity is as follows(some code was removed as to not make it too long):

public class RssUrl {
    @ManyToOne(fetch = FetchType.LAZY)
    private User user;

I've been following a relatively simple guide which I've found here.

Now my question is: How do I save the owning side entity?

Say I already have a user created.

User user = getCurrentUserDetails();

I add a new url for that user

user.addRssUrl(rssUrl);

And now what?

I've tried

    User user = getCurrentUserDetails();
    user.addRssUrl(rssUrl);
    rssUrlRepository.save(rssUrl);

But that results in an errror:

org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing

Of course, I could be going about this all wrong, perhaps my relationship is not correct to begin with?

I'm very open to ideas.

Upvotes: 1

Views: 721

Answers (1)

Ken Chan
Ken Chan

Reputation: 90527

You configure the relation between User and Url correctly. It mainly complains when it saves an Url , its User is a new record.

The problem can be fixed if you save the User first :

 User user = getCurrentUserDetails();
 user.addRssUrl(rssUrl);

 userRepository.save(user);
 rssUrlRepository.save(rssUrl);

But since you already configure cascade is ALL for User 's Url , all JPA operations applied on User will automatically applied to its Url too , which means you can simply do :

 User user = getCurrentUserDetails();
 user.addRssUrl(rssUrl);

 userRepository.save(user);

Upvotes: 3

Related Questions