多对一单向(数据库设计,多在在多方设计外键)
数据库设计:主键列不可分,联合主键不可有部分依赖,不能存在传递依赖
注解中在多方的类中加入一个"一方"的类,然后在方法之上加上@ManyToOne
XML中在多方的XML中设置<many-to-one name="一方的字段名" column="具体的外键名字">
注:在数据库中要生成的表要改名字,可以用@Table(name="")
第一种方法(一共会生成三张表,两张实体表,一张关系表)
多端:(生成一张表,存在一个外键comp_id)
@Entity()
public class Flight implements Serializable {
@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
@JoinColumn(name="COMP_ID")
public Company getCompany() {
return company;
}
...
}
一端:
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
publicSet<Student> getStudent() {
returnstudent;
}
publicvoidsetStudent(Set<Student> student) {
this.student= student;
}
第二种方法:(效果同第一种一样)
@Entity()
public class Flight implements Serializable {
@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, targetEntity=CompanyImpl.class )
@JoinColumn(name="COMP_ID")
public Company getCompany() {
return company;
}
...
}
public interface Company {
...
第三种方法
@Entity()
public class Flight implements Serializable {
@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
@JoinTable(name="Flight_Company",
joinColumns = @JoinColumn(name="FLIGHT_ID"),
inverseJoinColumns = @JoinColumn(name="COMP_ID")
)
public Company getCompany() {
return company;
}
...
}