一对多关联映射(注解)
@OneToMany
@Where:相当于set标签的where属性
@Cascade:相当于set标签的cascade属性
@OrderBy:相当于set标签的order-by属性
cascade:为级联操作,里面有级联保存,级联删除等,all为所有,配置多个格式为
Cascade={CascadeType.MERGE,CascadeType.REFRESH}
fetch: 加载类型,有lazy和eager两种
mappedBy:这个为manytoone中的对象名
使用@Cascade(value={org.hibernate.annotations.CascadeType.SAVE_UPDATE})指定级联操作
如果外键字段名和属性名不同,需要使用@JoinColumn注释指定外键字段名。
一对多单向映射关系注解
例如:t_person表与t_email表关系,即一个人可以有多个邮件
1、建立t_goodscates表
create table if not exists webdb.t_person(
id int(11) not null,
name varchar(30) not null,
PRIMARY key (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf-8 COLLATE=utf8_unicode_ci;
create table if not exists webdb.t_email(
id int(11) not null,
email varchar(30) not null,
persion_id int(11) not null,
PRIMARY key (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf-8 COLLATE=utf8_unicode_ci;
2、对应的实体
@Entity
@Table(name=”t_person”)
public class Person{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
@OneToMany(fetch=FetchType.EAGER,targetEntity=Email.class,mappedBy=”person”)
@Cascade(value={org.hibernate.annotations.CascadeType.ALL})
@JoinColumn(name=”person_id”)
@OrderBy(value=”email desc”)
Private List
. . .
}
@Entity
@Table(name=”t_email”)
public class Email{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String email;
. . .
}
一对多双向关联注解
@Entity
@Table(name=”t_customer”)
public class Customer{
private Integer id;
private String name;
private Set
@OneToMany(targetEntity=Order.class,mappedBy=”customer”)
@org.hibernate.annotations.Where(clause=”order_number=’2008012401’”)
@Cascade(value={org.hibernate.annotations.CascadeType.All})
@OrderBy(value=”number asc”)
Public Set
. . .
}
public class Order{
private Integer id;
private String number;
@ManyToOne(fetch=FetchType.EAGER,cascade={CascadeType.PERSIST})
@JoinColumn(name =”customer_id”)
private Customer customer;
. . .
}
多对一单向关联注解
@Entity
@Table(name=”t_orders”)
public class Order{
private Integer id;
private String number;
private Customer customer;
@ManyToOne(fetch=FetchType.EAGER)
@Cascade(value={org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@JoinColumn(name=”customer_id”)
Public Customer getCustomer(){}
. . .
}