-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 
Author Message
 Post subject: Child not persisting the FK
PostPosted: Mon Jun 26, 2017 6:41 pm 
Beginner
Beginner

Joined: Sun May 07, 2017 11:24 pm
Posts: 29
Hello,

I have the following entities:

Code:
public Episode() {}
@OneToMany(mappedBy = "episode", cascade=CascadeType.ALL)
private List<Stat> stats;

public Stat() {}

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne
private Offences code;
private Integer result;
private Boolean physicalInjury;
@ManyToOne
@JoinColumn(name = "episode_id")
private Episode episode;


However when I persist a Episode the Stat is saved, but episode_id (the FK) is empty ?

My understanding from SO answer here https://stackoverflow.com/questions/119 ... s-mappedby is that @JoinColum is normally the owner (Stat) and also has the FK attached?

What am I doing wrong?

Cheers

-AL


Top
 Profile  
 
 Post subject: Re: Child not persisting the FK
PostPosted: Tue Jun 27, 2017 12:08 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1630
Location: Romania
Most likely, you forgot to set both sides of the association.


Top
 Profile  
 
 Post subject: Re: Child not persisting the FK
PostPosted: Tue Jun 27, 2017 12:51 am 
Beginner
Beginner

Joined: Sun May 07, 2017 11:24 pm
Posts: 29
vlad wrote:
Most likely, you forgot to set both sides of the association.


So I note a number of things on your post that are different to my method:

1. Your collections is initialized with new ArrayList. So I should have:

Private List<Stats> stat = new ArrayList<>();

2. On the entity for the One side (Post in your case, Episode in mine) you have methods add and remove comment (so I should have add remove Stat).

3. I need to implement equals and hash-code methods on the child.

Assuming 1,2, and 3 are correct assumptions and I create them, the last thing I don't get is where the add/remove/equals/hashcode methods are subsequently called from?

Thanks in advance,

Al


Top
 Profile  
 
 Post subject: Re: Child not persisting the FK
PostPosted: Tue Jun 27, 2017 12:55 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1630
Location: Romania
All three findings are very important and I think your issue is caused by 2). Nevertheless, you should fix all of them because 3) is related to 2) when it comes to removing child entities, and 1) is just a best practice.


Top
 Profile  
 
 Post subject: Re: Child not persisting the FK
PostPosted: Tue Jun 27, 2017 4:37 am 
Beginner
Beginner

Joined: Sun May 07, 2017 11:24 pm
Posts: 29
vlad wrote:
All three findings are very important and I think your issue is caused by 2). Nevertheless, you should fix all of them because 3) is related to 2) when it comes to removing child entities, and 1) is just a best practice.


I had a go.

EPISODE
Code:
    public Episode() {}
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // Other fields
    @OneToMany(mappedBy = "episode", cascade=CascadeType.ALL)
    private List<Stat> stats = new ArrayList<>();

    // GETTERS & SETTERS

    public void addStat(Stat stat) {
        stats.add(stat);
        stat.setEpisode(this);
    }

    public void removeStat(Stat stat) {
        stats.remove(stat);
        stat.setEpisode(null);
    }
}


STAT
Code:
@Entity
public class Stat {

    public Stat() {}

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @OneToOne
    private Offences code;
    private Integer result;
    private Boolean physicalInjury;
    @ManyToOne
    @JoinColumn(name="episode_id")
    private Episode episode;

    // GETTERS SETTERS

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Stat )) return false;
        return id != null && id.equals(((Stat) o).id);
    }
    @Override
    public int hashCode() {
        return 31;
    }
}


Hopefully I am on the right track up until this point?

Then in the EpisodeService saveEpisode method I have:

Code:

    public Episode saveEpisode(Episode episode) {
       
       // OTHER STUFF

        for (Stat stat : episode.getStats()) {
            if (stat!=null) {
                //stat.setEpisode(episode);
                episode.addStat(stat);
            }
        }
        return episodeRepository.save(episode);
    }


But it did not like the for loop. Error was :

"java.util.ConcurrentModificationException: null

So I googled and tried a iterator, but the types were wrong for the episode.addStat(stat).

Suggestions?

Thank you again


Top
 Profile  
 
 Post subject: Re: Child not persisting the FK
PostPosted: Tue Jun 27, 2017 5:16 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1630
Location: Romania
You can't iterate a collection and modify it at the same time. This has nothing to do with Hibernate, it's just how Java Collections work.

However, this code you post makes no sense at all:

Code:
for (Stat stat : episode.getStats()) {
   if (stat!=null) {
      //stat.setEpisode(episode);
      episode.addStat(stat);
   }
}


1. Why do you expect a null child object?
2. Why do you want to re-add the same child references back to the list?

You should definitely reconsider your data access logic.


Top
 Profile  
 
 Post subject: Re: Child not persisting the FK
PostPosted: Tue Jun 27, 2017 5:37 am 
Beginner
Beginner

Joined: Sun May 07, 2017 11:24 pm
Posts: 29
vlad wrote:
You can't iterate a collection and modify it at the same time. This has nothing to do with Hibernate, it's just how Java Collections work.

However, this code you post makes no sense at all:

Code:
for (Stat stat : episode.getStats()) {
   if (stat!=null) {
      //stat.setEpisode(episode);
      episode.addStat(stat);
   }
}


1. Why do you expect a null child object?
2. Why do you want to re-add the same child references back to the list?

You should definitely reconsider your data access logic.


Right - my fault for not reading what I posted carefully, what I am trying to acheive is this side of the relationship :


Code:
for (Stat stat : episode.getStats()) {
      stat.setEpisode(episode);
}


Which doesn't use either the addStat or removeStat method I implimented the link you showed me? (When are those methods called?)

Trying to use an iterator:

Code:
        for (Iterator<Stat> stat = episode.getStats().iterator(); stat.hasNext();  ) {
                stat.setEpisode(episode);
        }
        return episodeRepository.save(episode);


But it says can't resolve method on setEpisode?

Thanks

Al


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.