thomas
thomas

Reputation: 51

How to implement many-to-many relationship in Java?

I'm working on a project that calculates the fee for volunteers, who worked at a party, depending on their working hours.

The following is true:

  • an employee can work at many party's
  • a party has many employees
  • an employee can choose how many hours he wants to work at a particular party.

eg: person A decides to work 4 hours at party A and 5 hours at party B, person B decides to work 3 hours at party A and 6 hours at party B. - It's important to know how many employees worked at a party, because the budget will be divided among the employees.

I want to calculate the fee for each volunteer on a given party How do I know who worked how many hours at which party? I think the code I have written now isn't the best option, because the objects get stored twice. If I remove the list of employees in the Party class, how do I know how many employees worked at the party?

public class Party {

private List<employee> employees;    
//other attributes

//methods
}

public class Employee {

private List<Hours> hours;    
// other attributes

//methods
}

public class Hours{

private Party party;    
private double hours;    
//other attributes

//methods
}

Upvotes: 4

Views: 3297

Answers (2)

Joakim Danielson
Joakim Danielson

Reputation: 51892

I don't see why you need the double reference between Party and Employee and the Hour class seems to represent the relation

public class Party {}

public class Employee {
    private List<Hours> hours;    
    public void addWork(Party party, int hours) {
        hours.add(new Hour(party, hours));
    }
}

public class Hours{
    private Party party;    
    private double hours;    
}

The above are your basic data classes but you also need some controller class(es) where you can create new employees and parties etc. Typical in such a class you would have a list of all employees so for instance to get all the hours worked at a specific party you could do given a list employees and a party p

List<Hours> hoursWorked = employess.stream().flatMap(e -> e.hours.stream()).filter(h->h.getParty().equals(p)).collect(Collectors.toList());

Upvotes: 0

birneee
birneee

Reputation: 663

define class that represent the relation

class Employment{
    private Party party;
    private Employee employee;
    private Hours hours;

    // ...
}

create list of employments

List<Employment> employments;

Upvotes: 1

Related Questions