Todos nós sabemos a resposta para a questão de quais relacionamentos entre entidades no Hibernate e JPA podem ser . Existem apenas quatro opções:
OneToOne - um para um
OneToMany - um para muitos
ManyToOne - muitos para um
ManyToMany - muitos para muitos
Cada um dos relacionamentos tem sua própria anotação e, ao que parece, você pode encerrar a conversa aqui, mas não é tão simples. De qualquer forma, pode haver algo simples no Hibernate ;) Cada uma das relações acima pode ser unidirecional ou bidirecional, e se você não levar isso em consideração, poderá enfrentar muitos problemas e esquisitices.
Por exemplo, vamos pegar duas entidades simples: um usuário e um contato. Obviamente, cada contato está associado a um usuário em um relacionamento muitos-para-um e a um usuário com contatos em um relacionamento um-para-muitos.
Relação unilateral
Um relacionamento unilateral é aquele pertencente a apenas uma das duas partes. Daí o nome. Deve-se notar que o outro lado não sabe nada sobre essa relação. O Hibernate irá considerar a entidade na qual a anotação de relacionamento será entregue como o dono do relacionamento.
Vamos tentar fazer com que o dono do relacionamento seja o contato. As entidades ficarão assim.
@Entity
@Table(name = "contacts")
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String type;
@Column
private String data;
@ManyToOne
private User user;
// , , ..
}
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String username;
// , , ..
}
Se você executar este código, o Hibernate criará a seguinte estrutura de tabela, que nos parece bastante familiar. O relacionamento entre as tabelas é criado usando o campo de referência user_id na tabela de contatos .
create table contacts (
id bigint not null auto_increment,
data varchar(255),
type varchar(255),
user_id bigint,
primary key (id)
) engine=InnoDB;
create table users (
id bigint not null auto_increment,
username varchar(128) not null,
primary key (id)
) engine=InnoDB
Contact . , , . . user Contact User. .
@Entity
@Table(name = "contacts")
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String type;
@Column
private String data;
// , , ..
}
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String username;
@OneToMany
private List<Contact> contacts;
// , , ..
}
, , Hibernate , .
create table contacts (
id bigint not null auto_increment,
data varchar(255),
type varchar(255),
primary key (id)
) engine=InnoDB;
create table users (
id bigint not null auto_increment,
username varchar(128) not null,
primary key (id)
) engine=InnoDB;
create table users_contacts (
User_id bigint not null,
contacts_id bigint not null
) engine=InnoDB;
Hibernate (join table) users_contacts, contacts, . , , Hibernate . , - .
JoinColumn contacts.
@OneToMany
@JoinColumn(name = "user_id")
private List<Contact> contacts;
user_id contacts, .
- (owning side) (inverse side). .. . , , . . .
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String username;
@ManyToMany
private List<Role> roles;
// , , ..
}
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@ManyToMany
private List<User> users;
// , , ..
}
. Hibernate , .
create table roles_users (
Role_id bigint not null,
users_id bigint not null
) engine=InnoDB;
create table users_roles (
User_id bigint not null,
roles_id bigint not null
) engine=InnoDB;
, . . Hibernate , , , . mappedBy. , , .
. . users Role .
// mappedBy - -
@ManyToMany(mappedBy = "roles")
private List<User> users;
Hibernate users_roles.
. , - (many), mappedBy @OneToMany
. ( Contact).
@Entity
@Table(name = "contacts")
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String type;
@Column
private String data;
@ManyToOne
private User user;
// , , ..
}
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String username;
@OneToMany(mappedBy = "user")
private List<Contact> contacts;
// , , ..
}
Hibernate .
! , , ! , !
Talvez haja uma sequência!