I think you might not be saving both sides of the relationship. Make sure both sides of the relationship hit a Session save.
I've got a little tutorial on my site. Check it out.
http://www.hiberbook.com/HiberBookWeb/learn.jsp?tutorial=18mappingonetomanyassociations
You'll notice I save both sides of the relationship between a player and a team:
Code:
import javax.persistence.*;
@Entity
public class Player {
private long id;
private String nickName;
private Team team;
@ManyToOne
@JoinColumn(name="team_id")
public Team getTeam() {return team;}
public void setTeam(Team t) {this.team = t;}
@Id
@GeneratedValue
public long getId() {return id;}
public void setId(long id) {this.id = id;}
public String getNickName() {return nickName;}
public void setNickName(String n) {nickName = n;}
}
import java.util.List; import javax.persistence.*;
@Entity
public class Team {
private long id;
private String name;
private List<Player> players;
@OneToMany(mappedBy="team",
targetEntity=Player.class,
fetch=FetchType.EAGER, cascade = CascadeType.ALL)
public List<Player> getPlayers() {return players;}
public void setPlayers(List<Player> p){players=p;}
@Id
@GeneratedValue
public long getId() {return id;}
public void setId(long id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
Session session = HibernateUtil.beginTransaction();
Team team = new Team();
Player p1 = new Player();
Player p2 = new Player();
session.save(team);
session.save(p1);
session.save(p2);
team.setName("Pickering Atoms");
p1.setNickName("Lefty");
p1.setTeam(team);
p2.setNickName("Blinky");
p2.setTeam(team);
HibernateUtil.commitTransaction();