Spring Data JPA多对多服务存储库问题

时间:2019-03-08 21:26:32

标签: java spring-mvc jpa

我正在尝试将ManyToMany实体添加到我的应用程序中。我创建了实体,但无法实现它。

演员班

@Entity
@Table(name = "actor")
public class Actor {

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

    @Column(nullable = false, name = "actor_name")
    private String actorName;

    @ManyToMany(mappedBy = "actor", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Movie> movie = new HashSet<Movie>();

    public Integer getId() {
        return id;
    }

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

    public String getActorName() { return actorName; }

    public void setActorName(String actorName) {
        this.actorName = actorName;
    }

    public Set<Movie> getMovie() {
        return movie;
    }

    public void setMovie(Set<Movie> movie) {
       this.movie = movie;
    }
}

电影课中,我有

@ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(
            name = "movie_actor",
            joinColumns = {@JoinColumn(name = "movie_id")},
            inverseJoinColumns = {@JoinColumn(name = "actor_id")}
    )
    Set<Actor> actor = new HashSet<Actor>();

........................

 public Set<Actor> getActor () {
        return actor;
    }

    public void setActor(Set<Actor> actor){
        this.actor = actor;
    }

我是这样创建我的实体的,但是在 MovieService ;

Actor actor = ActorRepository.findByActorName(movie.getActor().getActorName());
        movie.setActor(actor);

这部分给我错误。 movie.getActor()。getActorName()方法找不到。我需要看哪里?在IDE中,它也表示从未使用方法getActorName和setActorName。我还添加了ActorRepository和ActorService来更仔细地研究问题。

ActorRepository

public interface ActorRepository extends JpaRepository<Actor, Integer> {

    Set<Actor> findByActorName(String actorName);
}

ActorService

@Service
public class ActorService {

    private ActorRepository actorRepository;

    @Autowired
    public ActorService(ActorRepository actorRepository) {
        this.actorRepository = actorRepository;
    }

    public List<Actor> getAllActor() {
        return actorRepository.findAll();
    }
}

添加ManyToMany之后,我使用的是作为OneToMany实体。服务适用于OneToMany。如何将它们用于ManyToMany?我需要在电影中添加多个演员。我找不到用于ManyToMany实现的MVC项目。

1 个答案:

答案 0 :(得分:0)

您正在调用movie.getActor().getActorName(),它基本上是对getActorName()对象执行Set<Actor>

您基本上将这种关系视为ManyToOne而不是OneToMany

您可以使用以下内容来提取Actor中的第一个Set

ActorRepository.findByActorName(movie.getActors().iterator().next().getActorName());

但是,当然,您并没有全部Actor的名字

您可以做的是以下

public interface ActorRepository extends JpaRepository<Actor, Integer> {

    Set<Actor> findByActorNameIn(List<String> actorName);
}

并以这种方式调用

ActorRepository.findByActorNameIn(
    movie.getActors()
         .stream()
         .map(Actor::getName)
         .collect(Collectors.toList())
);