JPA ManytoOne和OneToMany的关系并不持久

时间:2011-12-17 22:57:46

标签: java jpa jpa-2.0

我有两个实体,一个比赛和一个团队:

竞争:

@Entity
public class Team implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
int id;

@Column(length=255)
String name;

@ManyToOne(optional=true)
Competition nextCompetitionAttending;
List<SiteUser> teamMembers;

nextComeptitionAttending由以下方法设置:

public void setNextCompetitionAttending(Competition nextCompetitionAttending) {
    this.nextCompetitionAttending = nextCompetitionAttending;
    nextCompetitionAttending.addTeam(this);
}

竞争如此定义:

@Entity
public class Competition implements Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
int maxTeamSize;
String name;

@OneToMany(mappedBy="nextCompetitionAttending" )
List<Team> teamsAttending;

我的持久性代码如下所示:

             utx.begin();
        EntityManager em = emf.createEntityManager();
        em.merge(user);
        Competition c = em.find(Competition.class, id);
        Team teamon = user.getTeamOn();
        teamon.setNextCompetitionAttending(c);
        System.out.println("Set next");
        em.flush();
        utx.commit();
        em = emf.createEntityManager();
        Team t = em.find(Team.class, teamon.getId());
        System.out.println(t.getNextCompetitionAttending());

在数据库中,“NEXTCOMPETITIONATTENDING_ID”列为空,我在尝试调试此代码的代码末尾的println也是如此。

为什么不坚持?

1 个答案:

答案 0 :(得分:4)

罪魁祸首可能是这一行:

em.merge(user);

user是一个分离的实体,您将其合并。然后,您从用户那里获得团队。但合并不会使分离的实体附加。它加载附加的用户,将状态从分离的用户复制到附加的用户,并返回附加的用户。因此,您正在进行的所有后续更改都将对分离的实体完成。

替换此行
user = em.merge(user);