如何使hibernate一次性将实体数据保存到所有相关表?

时间:2015-02-23 00:12:19

标签: java hibernate

我使用额外的表TeamTeamMemberteam_member之间建立了多对多关系。 Hibernate仅将数据保存到忽略member的{​​{1}}表。如何使它工作?

DAOImpl

team_member

儿童实体

public void addTeamMember(TeamMember teamMember) {
        getCurrentSession().save(teamMember);
    }

父实体

@Entity
@Table(name="member")
public class TeamMember {
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "teamMembers", cascade = CascadeType.ALL)
    public Set<Team> getTeams() {
        return teams;
    }

    public void setTeams(Set<Team> teams) {
        this.teams = teams;
    }
}

1 个答案:

答案 0 :(得分:0)

当您在TeamMember上编写mappedby时,您告诉JPA,团队将负责管理此关系。这意味着您必须将“成员”手动添加到“团队”列表中以使其失效(cascadeType都会确保它)。

TeamMember member = new TeamMember()...

EM.getTransactio().beging(); //if manage transactions manually
Team team = EM.find(Team.class,id);
team.getTeamMembers().add(member);
EM.getTransaction().commit();