Returing List vs Set of Entity in Spring Data JPA

16 Views Asked by At

I have 2 Entity classes which looks like below (User & Address, Just for example)

@MappedSuperclass
@Getter
@Setter
@DynamicUpdate
@JsonInclude(JsonInclude.Include.NON_NULL)
@NoArgsConstructor
@ToString
@Entity(name = "userPublish")
@Table(name = "user")
@IdClass(UserId.class)
@Immutable
@JsonTypeName("userSnapshotEntity")
 public class User {

  @Id
  @Column(name = "user_id", nullable = false, updatable = false)
  private String userId;

  @Id
  @Column(name = "country_code", nullable = false, length = 3, updatable = false)
  private int countryCode;  

  @JsonManagedReference
  @JsonIgnoreProperties("user")
  @OneToMany(
      fetch = FetchType.EAGER,
      cascade = CascadeType.ALL,
      orphanRemoval = true,
      targetEntity = Address.class,
      mappedBy = "user")
  private Set<Address> addresses = new HashSet<>();
 }

and child Address Entity which looks like below:

@NoArgsConstructor
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = false)
@IdClass(AddressId.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Entity(name = "addressPublish")
@Table(name = "address")
@Immutable
@MappedSuperclass
@Getter
@Setter
@DynamicUpdate
public class Address {

  @ManyToOne(fetch = FetchType.LAZY)
  @JsonBackReference
  @ToString.Exclude
  private User user = null;
}

Now, I have a method in my Repository as below:

@Repository
public interface UserSnapshotRepository
    extends CrudRepository<User, UserId> {

  @Query(
      value =
          "select * from user u LEFT JOIN address a ON u.country_code = a.country_code  AND u.user_id = a.user_id WHERE u.user_id IN (:userId) AND u.country_code = :country",
      nativeQuery = true)
  List<User> get(Collection<String> userId, int country);
}

Now, Suppose in my adress table, one user is having 3 address records, then my assumption was that this method will give me ONE User Object for that user which internally will have 3 address Object, but this method is giving me 3 User Objects in the List and each of them are exactly same having 3 address records,

One more observation, In the repository method, if I change the return type from List to Set then it is giving me correct one User record with 3 Addresses,

0

There are 0 best solutions below