在关系的两边非法使用mappedBy

时间:2015-09-14 04:44:31

标签: java spring hibernate

我想部署我的应用程序,但它显示错误:

org.springframework.beans.factory.BeanCreationException:创建名称为' entityManagerFactory'的bean时出错在com.springapp.mvc.config.HibernateConfig中定义:调用init方法失败;嵌套异常是org.hibernate.AnnotationException:在关系的两端非法使用mappedBy:com.springapp.mvc.models.User.ads

我认为我错了地图:

模特用户:

      @Entity
            public class User implements UserDetails {
               private int id;
               private Set<Ad> ads;
               private Set<Ad> favourites;

               @Id
               @GeneratedValue
               @Column(name = "id")
               public int getId() {
                  return id;
               }

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

                 @OneToMany(fetch=FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
            @Where(clause="is_deleted <> '1'")
            @JsonIgnore
            public Set<Ad> getAds() {
                return ads;
            }

            public void setAds(Set<Ad> ads) {
                this.ads = ads;
            }

            @ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
            @JsonIgnore
            @JoinTable(name= "favourite",
                joinColumns = {@JoinColumn(name="user_id")},
                inverseJoinColumns = {@JoinColumn(name="ad_id")})
            public Set<Ad> getFavourites() {
                return favourites;
            }

            public void setFavourites(Set<Ad> favourites) {
                this.favourites = favourites;
            }
    }

广告模式:

     @Entity
        public class Ad {

        private Integer id;

        @Id
        @GeneratedValue
        @javax.persistence.Column(name = "id")
        public Integer getId() {
            return id;
        }

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

        @ManyToOne
        @JoinColumn(name="user_id")
        public User getUser() {
            return user;
        }

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

        @ManyToMany(mappedBy = "ads")
        public List<User> getFavouriteUsers() {
            return favouriteUsers;
        }

        public void setFavouriteUsers(List<User> favouriteUsers) {
            this.favouriteUsers = favouriteUsers;
        }
}

哪里可能有问题

1 个答案:

答案 0 :(得分:1)

在User.java中,您已为&#34; ads&#34;定义了OneToMany关系。使用Ads.java

        @OneToMany(fetch=FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
        @Where(clause="is_deleted <> '1'")
        @JsonIgnore
        public Set<Ad> getAds() {
            return ads;
        }

但是,在Ads.java中,您已为同一

定义了ManyToMany关系
    @ManyToMany(mappedBy = "ads")
    public List<User> getFavouriteUsers() {
        return favouriteUsers;
    }

确保在两个类中使用相同的映射以避免此错误