Chave composta no hibernate

4 respostas
V

Qual o melhor metodo pra fazer uma chave que funcione desse jeito:

id_pai id_filho 1 1 1 2 2 1 2 2 2 3
Isso na tabela filho, com id_pai sendo chave estrangeira.

4 Respostas

T

Segue um exemplo. Imagine um relacionamento EMPRESA possui USUÁRIOS:

<class name="User" table="USER">
  <composite-id name="userId" class="UserId">
    <key-property name="userName"
     column="USERNAME"/>
    <key-many-to-one name="organization"
     class="Organization"
     column="ORGANIZATION_ID"/>
  </composite-id>
  <version name="version"
  column="VERSION"
  unsaved-value="0"/>
...
</class>
V

Olhando esse codigo:

O que tem na classe UserId ?

T
public class UserId extends Serializable {
 private String username;
 private String organizationId;
 
 public UserId(String username, String organizationId) {
   this.username = username;
   this.organizationId = organizationId;
 } 
 
 // Getters...
 
 public boolean equals(Object o) {
   if (this == o) return true;
   if (o = null) return false;
   if (!(o instanceof UserId)) return false;
   final UserId userId = (UserId) o;
   if (!organizationId.equals(userId.getOrganizationId()))
     return false;
   if (!username.equals(userId.getUsername()))
     return false;
   return true;
 }

public int hashCode() {
  return username.hashCode();
)
}"

We could save a new instance using this code:

UserId id = new UserId("john", 42);
User user = new User();
// Assign a primary key value
user.setUserId(id);
// Set property values
user.setFirstname("John");
user.setLastname("Doe");
session.saveOrUpdate(user); // will save, since version is 0
session.flush();

The following code shows how to load an instance:

UserId id = new UserId("john", 42);
User user = (User) session.load(User.class, id);

(Hibernate in Action, pág 334-335)

P

isso tudo deve funcionar se nenhum dos campos da pk composta for auto increment…

:roll:

Criado 30 de junho de 2005
Ultima resposta 8 de jul. de 2005
Respostas 4
Participantes 3