JPA @多对一、@一对多双向关系

ezykj2lf  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(166)

我正在研究双向Map。我用@OneToOne和@ManyToMany注解Map了Team和Member。

@Entity
public class Team {
    @Id @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "team")
    private List<Member> members=new ArrayList<Member>();

    //omit getter, setter ,toString

}

@Entity
public class Member {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name="USERNAME")
    private String name;

    @ManyToOne
    @JoinColumn(name="TEAM_ID")
    private Team team;

    @Enumerated(EnumType.STRING)
    private Status status;

    //omit getter, setter , toString

}

主方法

public static void main(String args[]){
    //...
    Team team= new Team();
    team.setName("RedTeam");
    em.persist(team);

    Member member= new Member();
    member.setName("me");
    member.setStatus(Status.ADMIN);
    member.setTeam(team);
    em.persist(member);

    Member findmember= em.find(Member.class, member.getId());
    Team findTeam= findmember.getTeam();
    System.out.println("members: "+findTeam.getMembers());

    //...
}

结果:
成员:[]
我想知道为什么在上面的代码中没有将“members”添加到“Team”的“members field”中。

tp5buhyn

tp5buhyn1#

这些是使其正常工作所需的最小更改

@Entity
public class Team {
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private @Id Long id;

    private String name;

    @OneToMany(mappedBy = "team", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Member> members = new ArrayList<>();

    public String getName() {
        return name;
    }

    public void setName(String pName) {
        name = pName;
    }

    public void addMember(Member m) {
        getMembers().add(m);
        m.setTeam(this);
    }

    public void removeMember(Member m) {
        getMembers().remove(m);
        m.setTeam(null);
    }

    public List<Member> getMembers() {
        return members;
    }
} 

        Team team = new Team();
        team.setName("RedTeam");
        // em.persist(team);

        Member member = new Member();
        member.setName("" + new Random().nextInt(999999));

        team.addMember(member);

        em.persist(team);

        Member findmember = em.find(Member.class, member.getId());
        Team findTeam = findmember.getTeam();
        System.out.println("Members: " + findTeam.getMembers());

相关问题