I have a similar scenario that uses a Team and Players in a free tutorial on my website. Just replace Team with User and Players with Departments, and you'll have all of the required associations.
http://jpa.ezhibernate.com/Javacode/learn.jsp?tutorial=18mappingonetomanyassociations
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;}
}
Code:
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;}
}
You will need a FK in the database. You can just have Hibernate create the association by calling the create method of the SchemExport class. It's pretty easy to do with Hibernate.
Here's the SQL code I actually used to create the tables. You could use this as a template if you want:
Code:
CREATE TABLE 'examscam'.'player'
('id' bigint(20) NOT NULL auto_increment,
'nickName' varchar(255) default NULL,
'team_id' bigint(20) default NULL,
PRIMARY KEY ('id'),
KEY 'FK8EA387017289A91D' ('team_id'));
CREATE TABLE 'examscam'.'team'
( 'id' bigint(20) NOT NULL auto_increment,
'name' varchar(255) default NULL,
PRIMARY KEY ('id'));