简体   繁体   中英

How can I search one Entity(in a Map) with an other Entity in SpringBoot?

I have an entity "User" and an entity "Worker". Now the entity worker has a map "timeMap" in which <LocalTime, User> is stored.

The "User" should "book" a worker with the authentication code at a certain time. The "worker" can then see which "user" has registered at which time and the "user" can see at which time he has registered with which "worker".

UserClass:

@Entity
public class User implements Serializable {

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

private String firstname;

private String surename;

private String email;

@Column(unique = true, name = "authCode")
private String authCode;

@SuppressWarnings("unused")
public User() {
}

public User (String firstname, String surename, String email, String authCode) {
    this.firstname= firstname;
    this.surename= surename;
    this.email = email;
    this.authCode = authCode;
 }
...
}

WorkerClass:

@Entity
public class Worker implements Serializable {
@Id
@GeneratedValue
private long id;

@Column(unique = true, name = "worker_id")
private String username;

private String firstname;

private String surename;

private String email;

private String password;

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "worker_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();

@OneToMany(cascade = CascadeType.ALL)
private Map<LocalTime, User> timeList;

@SuppressWarnings("unused")
public Worker() {
}


public Worker(String firstname, String surename, String email, String password, Set<Role> roles) {
    this.firstname = firstname;
    this.surename = surename;
    this.email = email;
    this.password = password;
    this.roles = roles;
    this.username = createUsername();
}
...

What is the best way to write a method in the repository(or later in my service class) to search all workers with a "user" and return a Map<LocalTime, Worker> containing all booked times and the worker, which the user has booked?

eg The user enters his Auth Code. This will search the UserRepository for the User Entity. This should now be used to search in the WorkerRepository for all map entries of all Worker Entites for the user and his time.

eg

Map of Worker1-> (5:00, User1; 5:10, User2; 5:20, User3)

Map of Worker2-> (5:20, User1; ....)

Result for User1: User1 --> (5:00, Worker1; 5:20, Worker2)

This should work (if your project is running on Java / JDK version 1.8+). I wasn't able to test it though. I hope this works for you:

User userToUseAsFilter = /*<The user reference you want to search for>*/;

Map<LocalTime, Worker> map =
        workerList.stream()
                  .flatMap(w -> w.getTimeList().entrySet().stream()
                                 .map(ue -> new EntryHolder(w, ue.getKey(), ue.getValue())))
                  .filter(eh -> Objects.equals(eh.user, userToUseAsFilter))
                  .collect(Collectors.toMap(
                          eh -> eh.time,
                          eh -> eh.worker,
                          (w1, w2) -> w1 // Cannot combine two workers into one instance, therefore just ignore worker 2 if they both have the same local time
                  ));

You also need the following class to temporarly hold a few values:

public class EntryHolder {
    public final Worker worker;
    public final LocalTime time;
    public final User user;

    public EntryHolder(Worker worker, LocalTime time, User user) {
        this.worker = worker;
        this.time = time;
        this.user = user;
    }
}

You should also add an equals method inside of your user class, in oder to actually find the user inside the map (I used the generate feature in IntelliJ to generate these two methods automatically):

public class User implements Serializable {
    ... // All of your fields are here
    
    // Auto generated using IntelliJ:
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id == user.id && Objects.equals(firstname, user.firstname) && Objects.equals(surename,
                                                                                            user.surename) && Objects
                .equals(email, user.email) && Objects.equals(authCode, user.authCode);
    }

    // Auto generated using IntelliJ:
    @Override
    public int hashCode() {
        return Objects.hash(id, firstname, surename, email, authCode);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM