@Don_Conteo

При попытке извлечь данные из связанной таблицы вылетает ошибка 500?

Суть вопроса:
Есть приложение, в котором пользователи могут сохранять рецепты. Есть две таблицы:
1 - рецепты
2 - пользователи
В рецептах есть колонка user_id по которой она связывается с пользователем, который сохранил этот рецепт. Необходимо сделать так, чтобы каждый юзер видел только те рецепты, которые он добавил сам и не видел рецептов остальных юзеров.

Вот мой код, вылетает ошибка
type=Internal Server Error, status=500
SQLGrammarException: could not extract ResultSet

Что в моем коде не так для осуществления задуманного?

Мой контроллер:
@GetMapping("/recipes/user/{id}")
    public String recipesView(@AuthenticationPrincipal User user, @PathVariable(value = "id") long id, Model model) {
        long userId = user.getId();
        Iterable<Reciepe> recipes = reciepeRepo.getRecipesForUser(userId);
        model.addAttribute("reciepes", recipes);
        model.addAttribute("user", user.getUsername());
        return "recipes";
    }


Мой репозиторий рецептов:
@Repository
public interface ReciepeRepo extends JpaRepository<Reciepe, Long> {

    @Modifying
    @Transactional
    @Query(value = "select r from reciepes_model as r where r.user_id=:user_id", nativeQuery = true)
    Iterable<Reciepe> getRecipesForUser(@Param("user_id") long id);

}


Мой репозиторий юзеров:
public interface UserRepo extends JpaRepository<User, Long> {
    User findByUsername(String name);
}


Рецепты:
@Entity
@Table(name = "reciepes_model")
public class Reciepe {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String reciepe;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private User user;

    private String info;
    private int weight, calories;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getReciepe() {
        return reciepe;
    }
    public void setReciepe(String reciepe) {
        this.reciepe = reciepe;
    }

    public int getWeight() {
        return weight;
    }
    public void setWeight(int weight) {
        this.weight = weight;
    }

    public int getCalories() {
        return calories;
    }
    public void setCalories(int calories) {
        this.calories = calories;
    }

    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }

    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }

    public Reciepe() {
    }

    public Reciepe(String name, String reciepe, int weight, int calories, String info, User user) {
        this.name = name;
        this.reciepe = reciepe;
        this.weight = weight;
        this.calories = calories;
        this.info = info;
        this.user = user;
    }
}


Юзеры (вряд ли они кому-либо потребуются, но на всякий случай скину тоже):
@Entity
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;
    private String password;

    @Enumerated(EnumType.STRING)
    @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "roles")
    private Set<Role> roles = new HashSet<>();

    @Override
    public String getPassword() {
        return password;
    }
    @Override
    public String getUsername() {
        return username;
    }
    private Collection<? extends GrantedAuthority> getRoles() {
        return roles;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getRoles();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }
    @Override
    public boolean isEnabled() {
        return true;
    }

    public Long getId() {
        return id;
    }
}
  • Вопрос задан
  • 45 просмотров
Решения вопроса 1
@galaxy
Наверное
select * from reciepes_model as r where r.user_id=:user_id
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы