使用userId创建对象列表

时间:2017-12-02 12:13:20

标签: java spring

我有一个应用程序,用户可以将电影标题添加到列表中。目前我使用此代码返回列表:

@Override 
public List<Movie> getAllmovies() {

    List<Movie> movies = new ArrayList<Movie>();
    Iterator<Movie> iterator = movieRepository.findAll().iterator();
    while (iterator.hasNext()) {
        movies.add(iterator.next());
    }

    return movies;
}

如您所料,这将返回当前用户的所有电影,而不是电影。所以我改为代码使用findAllByUserId()而不是findAll()

@Override 
public List<Movie> getAllmovies() {

    User current_user = userService.getUser();  
    List<Movie> movies = new ArrayList<Movie>();
    movies = movieRepository.findAllByUserId(current_user.getId());

    return movies;
}

我在MovieRepository中添加了方法:

@Repository
public interface MovieRepository extends JpaRepository<Movie, Serializable> {
    List<Movie> findAllByUserId(Long userId);
}

但是现在当我编译代码时,我得到了错误:

  

引起:org.springframework.data.mapping.PropertyReferenceException:找不到类型为Movie的属性userId!您的意思是&#39;用户&#39;

此错误来自哪里?它不是MovieRepository中的userId参数。

//编辑。搞砸了一下后,我发现userIdfindAllByUserId()方法有关。因此错误意味着我无法使用userId,因为它不是Movie类型的属性。那么如何按用户ID返回电影列表?

//编辑。添加了电影模型:

package com.movieseat.models;

import com.movieseat.model.security.User;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity(name = "Movie")
@Table(name = "movie")
public class Movie {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Integer id;

    private String name;

    public Movie(){}

    public Movie(String name) {
        this.name = name;
    }

    public Movie(Integer id, String name ) {
        this.id = id;
        this.name = name;
    }

    public Movie(String name, Set<User> users){
        this.name = name;
        this.users = users;
    }    

    @ManyToMany(mappedBy = "movies")
    private Set<User> users = new HashSet<>(); 

    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString(){
        return "id: " + id + "name: " + name;
    }

}

1 个答案:

答案 0 :(得分:1)

您可能希望获得以下方法签名:

List<Movie> findByUsers_Id(Long id)

这是使用Spring Data JPA的属性表达式功能。签名Users_Id将转换为JPQL x.users.id

More info here