spring-data-jpamany-to-manynhibernate-mappingassociative-table

nested exception is org.hibernate.AnnotationException: mappedBy reference an unknown target entity property


Based on this tutorial I'm trying to create Many-to-Many Relationship Using a Composite Key Eventually I get the following error

The composite key itself have the following structure:

@Embeddable
@Data
public class MovieRatingsKey implements Serializable {

    @Column(name = "movieid")
    private Movies movieid;

    @Column(name = "userid")
    private Usrs userid;
}

Class Movies:

@Entity
@Data
public class Movies {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer movieid;

    /*not related to the question*/

    @OneToMany(mappedBy = "movieid", fetch = FetchType.LAZY)
    private Set<Ratings> rates = new HashSet<>();
}

User:

@Entity
@Data
public class Usrs {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer userid;

    @OneToMany(mappedBy = "userid", fetch = FetchType.LAZY)
    private Set<Ratings> rates = new HashSet<>();
}

Associative table:

@Entity
@Data
public class Ratings {
    @EmbeddedId
    private MovieRatingsKey id;
    
    /*not related to the question*/

    @ManyToOne
    @MapsId("movieid")
    @JoinColumn(name = "movieid")
    Movies movie;

    @ManyToOne
    @MapsId("userid")
    @JoinColumn(name = "userid")
    Usrs user;
}

Solution

  • In your Usrs you have used userid in mappedBy is should be user as shown below.

    @Entity
    @Data
    public class Usrs {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer userid;
    
        @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
        private Set<Ratings> rates = new HashSet<>();
    }