If you do not want join tables , you must use inheritance and register the foreign key in the Endereco
table. The superclass would look something like:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class ObjetoComEndereco {
@Id
private Long id;
@OneToMany(cascade = CascadeType.ALL, mappedBy="objetoComEndereco")
private List<Endereco> enderecos = Lists.newArrayList();
}
Note that mappedBy
is required. If not used, Hibernate will create an auxiliary table and use UNION
to retrieve the addresses.
The other classes extend ObjetoComEndereco
. For example:
@Entity
public class Cliente extends ObjetoComEndereco {
// Outros atributos...
}
The class Endereco
changes to:
@Entity
public class Endereco {
@Id
private Long id;
@ManyToOne
private ObjetoComEndereco objetoComEndereco;
}
Hibernate will only create 5 tables:
create table cliente (
id bigint not null,
primary key (id)
)
create table endereco (
id bigint not null,
objeto_com_endereco_id bigint,
primary key (id)
)
create table fiador (
id bigint not null,
primary key (id)
)
create table fornecedor (
id bigint not null,
primary key (id)
)
create table procurador (
id bigint not null,
primary key (id)
)
A proxy query, for example, produces this SQL:
/* criteria query */ select
this_.id as id1_4_0_,
from
procurador this_
As the address list is lazy , Hibernate makes another query when it is time to access it:
select
enderecos0_.objeto_com_endereco_id as objeto_c2_1_0_,
enderecos0_.id as id1_1_0_,
enderecos0_.id as id1_1_1_,
enderecos0_.objeto_com_endereco_id as objeto_c2_1_1_
from
endereco enderecos0_
where
enderecos0_.objeto_com_endereco_id=?
If it is eager the query changes to:
/* criteria query */ select
this_.id as id1_4_1_,
enderecos2_.objeto_com_endereco_id as objeto_c2_1_3_,
enderecos2_.id as id1_1_3_,
enderecos2_.id as id1_1_0_,
enderecos2_.objeto_com_endereco_id as objeto_c2_1_0_
from
procurador this_
left outer join
endereco enderecos2_
on this_.id=enderecos2_.objeto_com_endereco_id