весенние данные - как отфильтровать пользователей определенного userProfile по userProfileType? - PullRequest
0 голосов
/ 17 мая 2019

Мой User объект следует:

@Entity
@Table
public class User {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name = "id", unique = true, insertable = true)
    private String id;

    // non relevant attributes

    @ManyToMany(fetch = FetchType.EAGER)
    @Fetch(FetchMode.SELECT)
    @JoinTable(name = "user2userProfile",
            joinColumns = @JoinColumn(name = "userId"),
            inverseJoinColumns = @JoinColumn(name = "userProfileId"))
    private Set<UserProfile> userProfileSet;

    // getters and setters
}

Объект UserProfile следует:

@Entity
@Table(name = "userProfile")
public class UserProfile {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name = "id", unique = true, insertable = true)
    private String id;

    @Column(name = "type", length = 15, unique = true, nullable = false)
    private String type = UserProfileType.USER.getUserProfileType();

    // constructors, getter and setter
}

Перечисление UserProfileType равно

public enum UserProfileType {

    USER("USER"),
    READER("READER"),
    WRITER("WRITER"),
    ADMIN("ADMIN");

// constructor and getter
}

Мой UserJpaRepository:

public interface UserJpaRepository extends JpaRepository<User, String> {

    // non relevant code

    List<User> findAllByUserProfileType(UserProfileType userProfileType);
}

В том виде, в каком он сейчас находится, я получаю следующее сообщение об ошибке на консоли:

org.springframework.data.mapping.PropertyReferenceException: No property userProfileType found for type User!

Что является правильнымобъявление UserJpaRepository для получения списка пользователей, имеющих определенный UserProfileType (т. е. список всех пользователей, имеющих UserProfile типа READER)?

1 Ответ

1 голос
/ 04 июня 2019

Я не очень понимаю, почему вам нужно иметь отношение многих ко многим от вашего пользователя к вашему профилю пользователя. Так что, если мы исправим это отношение «многие к одному», например:

у пользователя:

@OneToMany(mappedBy = "user")
private Set<UserProfile> profiles;

в профиле пользователя:

@ManyToOne
@JoinColumn(name = "user_id")
private User user;

Вы можете просто настроить поиск по String type в своем репозитории UserProfile:

List<UserProfile> findAllByType(String type);

Если вы теперь выполните итерацию полученного списка, вы можете получить всех пользователей с определенным типом UserProfileType:

List<User> users = userProfileRepository.findAllByType(UserProfileType.USER.toString()).stream().map(profile -> profile.getUser()).collect(Collectors.toList());  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...