Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
Foreign Key sharing in Hibernate

My database is composed of two tables: Organisation and User, in a ManyToOne relationship, where an organisation can hold many users.

Before I share my problem, here are my entities:

@Entity
@Table(name = "organisation")
public class OrganisationEntity {
    @Id
    @Column(name = "orga_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    private String name;

    // Getters & Setters
}

-

@Entity
@Table(name = "\"user\"")
public class UserEntity {

    @Id
    @Column(name = "user_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NotNull
    private String email;

    @NotNull
    private String firstName;

    @NotNull
    private String lastName;

    @NotNull
    private String password;

    @ManyToOne(targetEntity = OrganisationEntity.class,cascade = CascadeType.ALL)
    @JoinColumn(name = "orga_id")
    private OrganisationEntity organisation;

    // Getters & Setters    
}

Here is my issue, when two users are assigned an organisation with the same name, said organisation is created twice in the Organisation table with 2 different ID's. I wish to assign an organisation's ID to a new user if it already exists.

So if users U1 & U2 are created with an organisation called O1, both should have the same orga_id and only one organisation entry should be created in the database.

How can that be achieved? And what is missing in my understanding of Hibernate?

On request, here is my service that creates the UserEntity upon user registration:

@Override
public UserInfo createUser(UserInfo newUser) {
    return mapper.map(userDao.save(mapper.map(newUser)));
}

I map the object with Mapstruct to a UserEntity and send it to my DAO in order to save it in my database.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Make sure that you don't assign a new Organisation instance each time a new user is created, but rather that you first query the DB for an existing organisation by name, and re-use the resulting entity for all related users if it's already there.

Additionally, for the sake of correctness, consider adding a UNIQUE constraint to the organisation.name column.

over 4 years ago · Santiago Trujillo Relatório

0

Since you don't want different Oraganisations for different users, it's better to remove @GeneratedValue(strategy = GenerationType.AUTO) from Id attribute of OrganisationEntity. This would prevent creating more Organisation entries in DB.

Also fetch OrganisationEntity object first and assign to UserEntity

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda