Home > Enterprise >  Java set only displays 1st element
Java set only displays 1st element

Time:10-20

I have the following code, where I need to populate a set with multiple objects that are instances of the same class (User). The problem is, I only get the first object when I log.

user = User.builder()
                .id(1L)
                .username("2397047")
                .nickname("test1")
                .build();
        anotherUser = User.builder()
                .id(2L)
                .username("23971948")
                .nickname("test2")
                .build();

        Set<User> userSet = new HashSet<>();

        userSet.add(user);
        userSet.add(anotherUser);

        System.out.println("User set from test "   userSet);

This code produces the following output

User set from test [User(id=1, nickname=test1, username= 2397047, password=null, roles=null, groups=null)]

Why am I unable to get the entire collection?

This is my User class

package com.chama.chamaservice.user;

import com.chama.chamaservice.BaseEntity;
import com.chama.chamaservice.Views;
import com.chama.chamaservice.config.ApplicationUserRole;
import com.chama.chamaservice.group.Group;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonView;
import lombok.*;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Builder
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class User extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonView(Views.Public.class)
    private Long id;
    @JsonView(Views.Public.class)
    private String nickname;
    @JsonView(Views.Public.class)
    private String username; // <- Unique user's phone number
    private String password;

    @ElementCollection(targetClass = ApplicationUserRole.class)
    @CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
    @Enumerated(EnumType.STRING)
    @Column(name = "role")
    private Set<ApplicationUserRole> roles;

    @JsonIgnore
    @ManyToMany(mappedBy = "groupMembers", fetch = FetchType.LAZY, targetEntity = Group.class)
    private Set<Group> groups = new HashSet<>();

}

CodePudding user response:

In the User class, @Data annotation which will implement @Getter, @Setter, @ToString method.

It will print all values in the Set.

CodePudding user response:

Found an answer, although it may not be the optimal solution. I annotated the User class with @EqualsAndHashCode

  • Related