hibernate关系注解映射

一对多(最好不要用单向关联,其实单向本身并无多大意义):

一方:
@OneToMany(targetEntity=Order.class,cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinColumn(name=”fk_customer_id”)

如果一方加了fetch=FetchType.EAGER,查单一的多方对象时,会多产生一条sql
targetEntity也可以写成mappedBy=”customer”(这里写的是多多中对一方的引用属性),表示由对方去维护外键关系。
注:一般会将fetch=FetchType.LAZY

多方:
@ManyToOne
@JoinColumn(name=”fk_customer_id”)
注:一般需要会将fetch=FetchType.LAZY,默认情况下多方会主动加载一方数据的。

配置实例(客户–>客户订单):
客户中的集合:
@OneToMany(targetEntity=Order.class,cascade=CascadeType.ALL)
@JoinColumn(name=”fk_customer_id”)
private Set orders = new HashSet();
客户订单中的客户:
//订单所属客户
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name=”fk_customer_id”)
private Customer customer;

二、多对一

比较简单,示例:注册用户—->城市
@ManyToOne(targetEntity=City.class, fetch=FetchType.LAZY)
@JoinColumn(name=”fk_city_id”)
private City city;

三、多对多

示例:游戏用户,用户组

1
2
3
4
5
6
7
//用户参加的组
@ManyToMany(fetch=FetchType.LAZY)
@Cascade(value={org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@JoinTable(name="t_user_group",joinColumns={@JoinColumn(name="fk_user_id")}
,inverseJoinColumns={@JoinColumn(name="fk_group_id")}
)
private Set<Group> groups = new HashSet<Group>();

而在用户组中:
//该小组 中所包含的用户

1
2
3
4
5
    @ManyToMany(mappedBy="groups")
@Cascade(value={org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@JoinTable(name="t_user_group",joinColumns={@JoinColumn(name="fk_group_id")}
,inverseJoinColumns={@JoinColumn(name="fk_user_id")}
)

三、一对一惟一外键关联

示例:husband—->wife
而husband中(外键在t_husband表中):
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name=”fk_wife_id”,unique=true)
private Wife wife;

wife对象中:
@OneToOne(mappedBy=”wife”,cascade=CascadeType.ALL)
private Husband husband;

注解方式与spring的整合:





com.lovo.edu.model
com.lovo.edu.test


关于序列类型主键的配置示例:
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator=”student_id”)
@SequenceGenerator(name=”student_id”, allocationSize=1, initialValue=1,sequenceName=”seq_student_id”)
private Long sid;
其它的一些主键生成方式:
@Id
@GenericGenerator(name=”idGenerator”, strategy=”uuid”)
@GeneratedValue(generator=”idGenerator”) //使用uuid的生成策略
同理:使用assigned策略则在strategy中指定 =”assigned”

枚举映射示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Entity
@Table(name="t_husband")
public class Husband {

//状态
public enum State {
haveMoney, noMoney
}

//状态
@Enumerated
@Column(name="f_state")
private State state = State.noMoney;