简体   繁体   English

JPA ManytoOne和OneToMany关系不持久

[英]JPA ManytoOne and OneToMany relationship not persisting

I have two entities, a Competition and a Team: 我有两个实体,一个竞赛和一个团队:

Competition: 竞争:

@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 is set by the following method: nextComeptitionAttending通过以下方法设置:

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

Competition is defined thusly: 竞争由此定义:

@Entity
public class Competition implements Serializable{

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

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

My persistance code looks like this: 我的持久性代码如下所示:

             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());

In the database, the column "NEXTCOMPETITIONATTENDING_ID" is null, as is the println at the end of the code which I've been using to try to debug this. 在数据库中,“ NEXTCOMPETITIONATTENDING_ID”列为null,我用来调试该代码的代码末尾的println也为null。

Why doesn't this persist? 为什么这种情况不持续?

The culprit is probably this line: 罪魁祸首可能是这一行:

em.merge(user);

user is a detached entity, and you merge it. 用户是一个独立的实体,您可以将其合并。 Then, you get the team from the user. 然后,您从用户那里获得团队。 But merge doesn't make the detached entity attached. 但是合并不会使分离的实体附加。 It loads the attached user, copy the state from the detached one to the attached one, and returns the attached one. 它加载附加的用户,将状态从分离的用户复制到附加的用户,然后返回附加的用户。 So, all the subsequent changes you're doing are done to the detached entity. 因此,您正在执行的所有后续更改都将对分离的实体进行。

Replace this line with 将此行替换为

user = em.merge(user);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM