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

241
Visualizações
How to connect @ManyToMany relationships in Spring

I am creating an application that uses a many to many relationship between employees and shifts. However, I am having difficulties in understanding how I can assign/connect an employee to a shift.

@Data
@Entity
public class Employee {

private @Id @GeneratedValue long employeeID;
private String Name;

@OneToMany(cascade = CascadeType.ALL)
private Set<Shift> shifts;

private Employee() {
}

public Employee(long employeeID, String Name) {
    this.employeeID = employeeID;
    this.Name = Name;
}

public Employee(long employeeID, String Name, Set<Shift> shifts) {
    this.employeeID = employeeID;
    this.Name = Name;
    this.shifts = shifts;
}

public void setShift(Set<Shift> shifts) {
    this.shifts = (Set<Shift>) shifts;
}

}

@Data
@Entity
public class Shift {

private @Id @GeneratedValue long Id;
private String shifts;

private Set<Employee> employee;

private Shift() {
}

public Shift(String shifts) {
    this.shifts = shifts;
}

public Shift(String shiftPeriod,Set<Employee> employee ) {
    this.shifts = shifts;
    this.employee=employee;
}

public void setEmployee(Set<Employee> employee) {
    this.employee = employee;
}

}

@Component
public class DatabaseLoader implements CommandLineRunner {

private final EmployeeRepository repository;

@Autowired
public DatabaseLoader(EmployeeRepository repository) {
    this.repository = repository;
}

@Override
public void run(String... strings) throws Exception {
    Shift shift = new Shift("Friday Morning");
    Employee employee = new Employee(0001, "Adam Smith");

    employee.setShift(shift);
    this.repository.save(employee);
}

}

public interface ShiftRepository extends CrudRepository<Shift, Long> 

public interface EmployeeRepository extends CrudRepository<Employee, Long>

Entities added into employees and shifts are saved but is there a way I can assign a shift to an employee in the DatabaseLoader class, as I've been stuck on finding a solution to this.

I know that I haven't included a method which attempts to connect employee and shifts but I don't how to approach this problem.

Thanks in advance

**EDIT: The new problem I have now is that I get the following message when trying to deploy in spring:

Unable to build Hibernate SessionFactory: Could not determine type for: java.util.Set, at table: shift, for columns: [org.hibernate.mapping.Column(employee)]

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

0

It seems that you are using Hibernate under the hood, then all you have to do is to set the objects you want to save properly, like this:

@Component
public class DatabaseLoader implements CommandLineRunner {

private final EmployeeRepository repository;
private final ShiftRepository shiftRepository;

@Autowired
public DatabaseLoader(EmployeeRepository repository, ShiftRepository shiftRepository) {
    this.repository = repository;
    this.shiftRepository=shiftRepository;
}

@Override
public void run(String... strings) throws Exception {
    Shift shift = new Shift("Friday Morning");
    Employee employee = new Employee(0001, "Adam Smith");

    employee.setShift(shift)
    this.repository.save(employee);
}

The only difference is that I attached between the two objects and only then I try to save them. It's worth to mention that it's important to use Cascade.All or Cascade.persiste in order that hibernate will do the inserts on both entities.

over 4 years ago · Santiago Trujillo Relatório

0

In my opinion:

  1. A shift is an independent entity. It does not depend on any employees. So Shift must not have a reference to Employee.

  2. On the other hand an employee depend on several shifts, so Employee must have unidirectional @OneToMany association with Shift.

    @OneToMany
    private List<Shift> shifts;
  1. And don't use cascading here because Employee and Shift are independent entities.

UPDATE

To "add a shift to an employee" we can use for example an Employee setter:

@Entity
public class Employee {
    //...
    private String name;
    //...
    @OneToMany
    private List<Shift> shifts;
    //...
    public Employee(String name) {
        this.name = name;
    }
    //...
    public setShifts(Shift... shifts) {
        this.shifts = Arrays.asList(shifts);
    }
    //...
}

then

Shift monday = shiftRepository.save(new Shift("Monday"));
Shift friday = shiftRepository.save(new Shift("Friday"));
Employee adamSmith = new Employee("Adam Smith");
adamSmith.setShifts(monday, friday);
employeeRepository.save(adamSmith);
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