我正在尝试在对象团队中保留一个列表。我无法让 JPA 为我坚持下去。在阅读了一些帖子之后,您似乎需要遍历 List<>,并单独保存每个帖子。这对我来说似乎不正确。JPA 必须有办法自动保留该列表。
我是否错过了一种简单的 JPA 方式来深度持久化这些对象?
团队班:
@Entity
@Table(name = "rahCLUB_TEAM")
public class Team implements Serializable{
....
@OneToMany(fetch=FetchType.EAGER, mappedBy = "team", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private List<Player> players;
...
}
球员等级:
@Entity
@PrimaryKeyJoinColumn(name="id")
@Table(name = "rahCLUB_PLAYER")
public class Player extends Individual implements Serializable{
...
@ManyToOne
@JoinTable(name="rahCLUB_PLAYER_TEAM_LINK")
private Team team;
...
}
JPAClubDAO测试:
//create a valid team code
...
Team team = new Team();
team.setName("Pittsburgh Pirates");
team.setLeague("NFL");
team.setGroup("group");
team.setLevel("AAA");
Player player = new Player();
player.setFirstName("firstNameA");
player.setLastName("lastNameA");
player.setEmail("emaila@email.com");
player.setLogin("loginA");
player.setJerseyNo(22);
player.setPosition("fullback");
Date dob =new SimpleDateFormat("dd/MM/yyyy").parse("21/11/1986");
player.setDob(dob);
Player playerb = new Player();
playerb.setFirstName("firstNameB");
playerb.setLastName("lastNameB");
playerb.setEmail("emailB@email.com");
playerb.setLogin("loginB");
playerb.setJerseyNo(15);
playerb.setPosition("widereceiver");
Date dobb =new SimpleDateFormat("dd/MM/yyyy").parse("06/06/1986");
playerb.setDob(dobb);
ArrayList<Player> players = new ArrayList<Player>();
players.add(player);
players.add(playerb);
team.setPlayers(players);
Team queryTeam = em.find(Team.class, team.getId());
log.debug("checking coach...");
这些都失败了:
assertTrue(queryTeam.getPlayers().size()>0);
assertNotNull(queryTeam.getPlayers().get(0));
assertTrue(queryTeam.getPlayers().size()==2);
添加此代码的代码:
@Override
public void createTeam(Team team) throws ClubDAOException {
em.persist(team);
for (Player player : team.getPlayers())
{
this.createPlayer(player);
//em.persist(player);
}