我正在尝试将List保留在对象Team中。我无法让JPA为我坚持下去。在阅读了一些帖子后,看起来您需要通过List<>进行迭代,并单独保留每个帖子。这对我来说似乎不对。 JPA必须有办法自动保持List的自动化。
我是否错过了一种简单的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;
...
}
JPAClubDAOTest:
//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);
}
答案 0 :(得分:3)
好吧,我要回答我自己的问题,因为我想在这里看到一个......
感谢JB Nizet为我解决这个问题/指向我正确的帖子,在这里:Understanding annotations and JPA(hibernate)
关键是必须设置反向关系。在上面的示例中,要修复它:
player.setTeam(team);
playerb.setTeam(team);
一旦设置了关系的两边,它就会持久存储到数据库中。
答案 1 :(得分:3)
您可以使用其他方法:
Unidirectional OneToMany: http://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Unidirectional_OneToMany.2C_No_Inverse_ManyToOne.2C_No_Join_Table_.28JPA_2.0_ONLY.29
您仍需要保留Object,然后将其添加到Collection中。