Search code examples
sqljpajoinjoincolumn

Get record from another table using JPA


I have been trying to figure out how to do this for sometime without any luck and have not managed to find anything useful while search on Google either.

I have THREE tables:

HOTEL
 - id
 - name
 - local_id (foreign key)

DESCRIPTION
 - id
 - description
 - hotel_id (foreign key)
 - locale_id (foreign key)

LOCALE
 - id
 - local

I also have the following HOTEL DAO model:

@Entity
@Table(name = "HOTEL")
public class Hotel implements Serializable {

    @Column(name = "id")
private long id;

    @Column(name = "description")
    private HotelDescription description;
}

Using JPA, how can I retrieve the data from table DESCRIPTION based on hotel_id and locale_id to populate description in DAO model hotel?


Solution

  • Well, you also have HotelDescription JPA entity, right? So you can define bidirectional mapping for entities.

    instead of

    @Column(name = "description")
    private HotelDescription description;
    

    you should have something like

    @OneToOne(mappedBy = "hotel", cascade = CascadeType.ALL)
    private HotelDescription desc;
    

    and on the other side, in HotelDescription you should have back mapping

    @OneToOne
    @JoinColumn(name = "hotel_id")
    private Hotel hotel;
    

    When you will extract Hotel entity, JPA will also fetch child entity (HotelDescription) for you.

    if you want to use @OneToMany mapping it will be (many descriptions for one hotel)

    @OneToMany(mappedBy = "hotel", cascade = CascadeType.ALL)
    private HotelDescription desc;
    

    and on the other side

    @ManyToOne
    @JoinColumn(name = "hotel_id")
    private Hotel hotel;
    

    In JPA you can use several types of mapping like OneToMany, ManyToMany... That's only basics. Find a tutorial. You may start here: http://docs.oracle.com/javaee/6/tutorial/doc/bnbqa.html (not the best one probably)

    Oh. And make sure you annotate id with @Id