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

竞争:

@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”列为null,我一直在尝试调试的代码末尾的println也为null。

为什么这种情况不持续?

最佳答案

罪魁祸首可能是这一行:

em.merge(user);


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

将此行替换为

user = em.merge(user);

10-04 18:05