(6)ManyToMany单向、双向:@JoinTable

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiangshangchunjiezi/article/details/78511907

一、manytomany单向
单向是指类层面,在下面例子中老师类可以知道要教哪些学生,学生不知被哪些老师教
**需要用到连接表**@JoinTable(name="t_s",
joinColumns={@JoinColumn(name="teacher_id")},inverseJoinColumns={@JoinColumn(name="student_id")}
)

也可以不用连接表,但是若不用连接表,表名、列名规则:
在student表中没有写外键则会用对方的表名_主键名
在teacher表中有外键,则会s_id(也是student的主键名)
表名是student_teacher
student类

@Entity
public class student {

    private int id;
    private String name;

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Teacher类

@Entity 

public class teacher {

    private int id;
    private String name;
    private Set<student> s=new HashSet<student>();



    @Id //必须加在getId上面
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    @ManyToMany
    @JoinTable(name="t_s",
    joinColumns={@JoinColumn(name="teacher_id")},inverseJoinColumns={@JoinColumn(name="student_id")}
    )//将会以上两个字段为联合主键
    //定义中间表的名称,列名:joinColumns,inverseJoinColumns是预防组合主键的时候。
    public Set<student> getS() {
        return s;
    }
    public void setS(Set<student> s) {
        this.s = s;
    }   
}

二、manytomany双向
也可以用@JoinTable对连接表字段名进行修改

@Entity
public class student {

    private int id;
    private String name;
    private Set<teacher> ts=new HashSet<teacher>();

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @ManyToMany
    @JoinTable(name="t_s",
    joinColumns={@JoinColumn(name="teacher_id")},inverseJoinColumns={@JoinColumn(name="student_id")}
    )
    public Set<teacher> getTs() {
        return ts;
    }
    public void setTs(Set<teacher> ts) {
        this.ts = ts;
    }



}
@Entity 

public class teacher {

    private int id;
    private String name;
    private Set<student> s=new HashSet<student>();



    @Id //必须加在getId上面
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }



    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @ManyToMany(mappedBy="ts")

    //定义中间表的名称,列名:joinColumns,inverseJoinColumns是预防组合主键的时候。
    public Set<student> getS() {
        return s;
    }
    public void setS(Set<student> s) {
        this.s = s;
    }


}
阅读更多
换一批

没有更多推荐了,返回首页