标签:
1)多对一映射关系(单向)
使用外键关联,在外键的选取上以多的一方为主,即外键要在多的一方体现出来
@Entity
public class Company implements Serializable{
@Id
@Column(name = "c_id")
private int id;
private String name;
}
@Entity
public class Employee implements Serializable {
@Id
@Column(name="e_id")
private int id;
private String name;
@ManyToOne
@JoinColumn(name = "c_id")
private Company company;
}
2)一对多
1.单向关联(以一的一方为主,即一对多关系要体现在一的一方)
创建中间表,以两张表的id字段为内容(hibernate的生成策略:在多的一方生成一个外键)
@Entity public class Company implements Serializable{ @Id @Column(name = "c_id") private int id; private String name; @OneToMany private Set<Employee> employee; }
@Entity
public class Employee implements Serializable {
@Id
@Column(name="e_id")
private int id;
private String name;
}
2.双向关联
不创建中间表,以在多的一方保存一个外键作为记录,体现一对多
**与单向不同的是,双向关联必须要在一的一方定义mappedby,指向多的一方
@Entity public class Company implements Serializable{ @Id @Column(name = "c_id") private int id; private String name; @OneToMany(mappedBy="companys") private Set<Employee> employees;
}
@Entity
public class Employee implements Serializable {
@Id
@Column(name="e_id")
private int id;
private String name;
@ManyToOne
private Company companys;
}
3)一对一
1.一对一主键关联(生成的表没有任何外加字段,也没有中间表,以ID的约束为主键)
@Entity
public class Company implements Serializable{
@Id
@Column(name = "c_id")
private int id;
private String name;
@OneToOne
@PrimaryKeyJoinColumn
private Boss boss;
}
@Entity
public class Boss {
@Id
private int id;
private String name;
@OneToOne(mappedBy="boss")
private Company company;
}
2.一对一外键关联(在主的一方A加入一个外键,并且该外键唯一,而在另一方B同样引入该规则,但不产生外键,仅使A的一方的主键也唯一)
@Entity
public class Company implements Serializable{
@Id
@Column(name = "c_id")
private int id;
private String name;
@OneToOne
@JoinColumn(name="boss_id" ,unique=true)
private Boss boss;
}
@Entity
public class Boss {
@Id
private int id;
private String name;
@OneToOne(mappedBy="boss")
private Company company;
}
标签:
原文地址:http://www.cnblogs.com/welv/p/5065266.html