Robert Yetman
Robert Yetman

Reputation: 11

JPA - How to map the relationship between two tables?

I'm new to JPA, and trying to figure out how to correctly map the following relationship between two database tables:

movies { id, title, rating }

ratings { id, rating }

So that querying the movies database will return the rating string ('g', 'pg', etc) from the second table for that movie. Each of these is their own @Entity and java class as shown below. Do I have to something in the getRating() method of the MovieCatalogEntity to get the correct rating?

    @Entity(name="movieCatalog")
    public class MovieCatalogEntity {

        @Id
        @Column(name="ID", nullable=false)
        private long id;

        @Column(name="Title", nullable=false)
        private String title;

            ??? What goes here ????????
            private RatingEntity rating;
    }


@Entity(name="Rating")
public class RatingEntity {

    @Id
    @Column(name = "id", nullable=false)
    private long id;

    @Column(name="Rating", nullable=false)
    private String rating;
}

Upvotes: 1

Views: 1050

Answers (2)

Premraj
Premraj

Reputation: 7902

See @OneToOne, @ManyToOne and @JoinColumn annotations

Upvotes: 1

RNJ
RNJ

Reputation: 15552

Something like this should do it assuming that a the same rating can appear on many Movies.

 @ManyToOne(optional=false) 
 @JoinColumn(name="rating_id", referencedColumnName = "ID", nullable=false)
 public RatingEntity rating

Details of the @ManyToOne are found here

Upvotes: 0

Related Questions