Hibernate annotation的关系定义

一、@OneToOne

[code]@Entity
public class User{
private Address address;

@OneToOne
public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}
}

@Entity
public class Address{
private User user;

@OneToOne(mappedBy = "address")
public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

}[/code]
1、两边都定义了@OneToOne,但都没有定义mappedBy,则user和address表都会生成到对方的外键,双方都是这个关系的拥有者。
2、两边都定义了@OneToOne,如果user定义了mappedBy,则在address表生成到user的外键,address是这个关系的拥有者;如果address定义了mappedBy,则在user表生成到address的外键,user是这个关系的拥有者。
二、@ManyToOne和@OneToMany

[code]@Entity
public class Employee {
private Department department;

@ManyToOne
public Department getDepartment() {
return department;
}

public void setDepartment(Department department) {
this.department = department;
}
}

@Entity
public class Department {
private Set<Employee> employees = new HashSet<Employee>();

@OneToMany(mappedBy="department")
public Collection<Employee> getEmployees() {
return employees;
}
public void setEmployees(Collection<Employee> employees) {
this.employees = employees;
}
}[/code]
@ManyToOne中Many指的是本类(也就是声明@ManeyToOne的类),One是指关联类,也就是To前边的对应本类,后边的对应关联类。如果方法返回的是单数关联类则定义@ManyToOne,例如:
[code]@ManyToOne
public Department getDepartment() {
return department;
}[/code]
方法返回的是Department,为单数关联类,对应@ManyToOne中的One;
如果返回的是复数关联类则定义@OneToMany,例如:
[code]@OneToMany(mappedBy="department")
public Collection<Employee> getEmployees() {
return employees;
}[/code]
方法返回的是Collection<Employee>,复数关联类,对应@OneToMany中的Many。其中定义mappedBy的是@OneToMany,也就是说One这一方是关系的拥有者。Many一方的表中生成到关联类的外键。

三、@ManyToMany

[code]@Entity
public class Book {
private Set authors = new HashSet<Author>();

@ManyToMany
public Set<Author> getAuthors(){
return authors;
}

Public void setAuthors(Set<Author> authors){
This.authors = authors;
}
}

@Entity
public class Author {
private Set books = new HashSet<Book>();


@ManyToMany(mappedBy="authors")
public Set<Book> getBooks(){
return books;
}

Public void setBooks(Set<Book> books){
This.books = books;
}
}
[/code]
@ManyToMany会生成中间表,具体表名和字段可以通过@AssociationTable来定义,默认的就可以了,同样关系的非拥有者,需要定义mappedBy属性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值