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.  [ 1 post ] 
Author Message
 Post subject: JPA OneToMany - Null foreign key?
PostPosted: Sat Oct 25, 2008 9:43 pm 
Newbie

Joined: Sat Oct 25, 2008 9:25 pm
Posts: 1
All,

I am using Hibernate JPA and am encountering difficulties persisting a one to many relationship.

Assume I have the following entities:

Team
Code:
@Entity
@Table(name="team")
public class Team implements Serializable {
  // ... attributes ...

  @OneToMany(mappedBy="team", cascade=CascadeType.ALL)
  private Set<Player> players = new HashSet<Player>();

  public void addPlayer(Player player) {
    players.add(player);
  }

  // ... methods - using POJO getters / setters ...
}


Player
Code:
@Entity
@Table(name="player")
public class Player implements Serializable {
  // ... attributes ...

  @ManyToOne(cascade=CascadeType.ALL)
  @JoinColumn(name="team_id")
  private Team team;

  public Team getTeam() {
    return team;
  }

  public void setTeam(Team team) {
    this.team = team;
  }

  // ... methods - using POJO getters / setters ...
}


In my code, I create a Team and add a Player to it as follows:

Code:
Player player = new Player();
player.setName("My player");

Team team = new Team();
team.setName("My team");

// NOTE: Foreign key *not* null if the following line uncommented
//player.setTeam(team);

team.addPlayer(player);

// Uses JPA persist method
teamDAO.saveTeam(team);


In the player table, the team_id column is being set to null and therefore there is no reference back to their team. Of course, if I uncomment the player.setTeam(team) method call, the team_id column is correctly set in the player table (as I would expect).

I thought Hibernate would automatically set the team_id column for each Player entity as they're added to the Set? Am I missing something?

Thanks!

Damian


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

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.